我使用 HTTP 客户端从 Laravel 中的 API 获取响应。这需要一些时间。我只是想计算有多少百分比的数据是从 API 获取的。当进度条 100% 完成时,意味着数据已完全获取并准备好显示。那么有什么解决办法吗?
如果你那么灵活,那么你可以这样做;) 您可以使用带有 livewire 和 tailwind css 的队列作业来实现此目标。
composer require livewire/livewire
。php artisan make:livewire YourClassWire
创建livwire类,你可以在/App/Http/Livewire下找到它。class YourClassWire extends Component
{
public $visibility;
// you need this to hide progress bar if it is 100% or 0
public $progress ;
// this will be your progress.
public $total ;
// this is your total job
protected $listeners = ['reresh']; // this will called from the view
public function mount()
{
$this->total = \DB::table('jobs')->count(); // you must change this if you have multiple queue with different names
$this->visibility = $this->total > 0 ? 'visible' : 'hidden' ; // we need it to show hide porgress ;
$this->progress = \DB::table('jobs')->count() * 100 / $this->total; // simple equation to get progress percentage
$this->render(); // you now call render each time the view refresh
}
public function refresh()
{
// this function will be responsible from updating the progress
$this->visibility = $this->total > 0 ? 'visible' : 'hidden' ; // we need it to show hide porgress ;
$this->progress = \DB::table('jobs')->count() * 100 / $this->total; // simple equation to get progress percentage.
}
public function render()
{
return view('livewire.your-class-wire',) // note this will created with command you executed earlier `php artisan make:livewire YourClassWire` and you can find it in view/livewire
->with('progress', $this->progress)
->with('visibility',$this->visibility);
}
}
<div wire:poll.2s="refresh">
<div class="{{$visibility}}">
<div class=" progress_main flex w-3/6 bg-gray-200 rounded-full h-1 mb-4 dark:bg-gray-700">
<!-- controll the width with the progress -->
<div class= "progressbar border-0 relative align-middle bg-gradient-to-r from-[#d72323] via-[#dddd03] to-[#248401] dark:bg-[#dcf5ff] h-1 rounded-full" style="width: {{ $progress }}%">
<div class="overflow-hidden absolute bottom-[-9px] flex items-center right-0 mr-[-60px] z-30 h-6 text-2xl text-[#f36d1f]">✈️
<!-- now this text icon will move to the end based on your progress -->
</div>
</div>
</div>
</div>
</div>
我希望这能引导您实现您想要的..成功
你可以做一些类似的逻辑:
get data from API
foreach dataset taken, do the calculation
after the calculation store/update model
get out of the foreach loop or take the next entry
或者如果你需要计算平均值或类似的东西,你可以去
$emptyArray = [];
foreach($responses as $response) {
$emptyArray [$response->id][] = $response->data; // data === type of integer
}
$emptyArray_avg = [];
foreach($emptyArray as $arrEl) {
$emptyArray_avg[] = array_sum($arrEl)/count($arrEl);
}
注意: 如果 JSON 响应中有大量数据,队列将是一个很好的解决方案:)