如何在Subscribe方法中访问组件变量

时间:2019-01-17 20:31:02

标签: angular

我试图在调用Service之前显示一个加载微调器。如果服务失败,则应隐藏加载微调器。

我能够显示微调器,但无法隐藏它,因为在subscription方法中无法访问组件变量。有什么办法解决吗?

import { Component, OnInit } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
import { Observable } from 'rxjs/Observable';
import { NgxSpinnerService } from 'ngx-spinner';
import { FoodService } from '../../../services/food.service';

import { Food } from '../../../interfaces/Food';

@Component({
  selector: 'app-food',
  templateUrl: './food.component.html',
  styleUrls: ['./food.component.css']
})
export class FoodComponent implements OnInit {

  foodContents$: Observable<Food>
  public foodPageId : any;
  public spinnerStatus: boolean = false;
  public foodRequest;

  constructor(private foodService:FoodService, private route: ActivatedRoute, private spinner: NgxSpinnerService) { 
    this.route.params.subscribe(res => this.foodPageId = res.id);
  }

  ngOnInit() {
    if(!this.foodRequest)
    {
      this.spinner.show();
      this.spinnerStatus = true;
      this.foodContents$ = this.foodService.GetFoodPageContent(this.foodPageId);
      this.foodContents$.subscribe({
        error(err) {
          /*Not able to access spinner and spinnerStatus variables.
          How to access these?*/
          this.spinner.hide();
          this.spinnerStatus = false;
        }
      }); 
    }
  }

}

2 个答案:

答案 0 :(得分:2)

您的this没有指向正确的范围。 How to access the correct `this` inside a callback?

您可以使用箭头功能解决该问题:

  .subscribe({
    error: () => {
      this.spinner.hide();
      this.spinnerStatus = false;
    }
  });

这样,this现在指向组件,这意味着您可以访问变量。

但是我会...可以在finalize中调用这些命令(使用rxjs 6),尽管发生了错误或成功,仍会调用它们:

this.foodContents$.pipe(
  finalize(() => {
    this.spinner.hide();
    this.spinnerStatus = false;
  })
 )
  .subscribe((data: SomeModel) => {
    // success, do something with data
  },
  (err) => {
    // error, do something..
 }));

通常,当错误或成功发生时,我们通常还会做其他事情。

答案 1 :(得分:1)

处理错误like this(错误处理函数应为第二个参数):

this.foodContents$.subscribe(()=>{},
 (err) => {
    this.spinner.hide();
    this.spinnerStatus = false;
  }
); 

如果您还想使用finnaly(最后尝试捕获),则还可以将第三个函数作为subscription('onCompleted')的最后一个参数。

更新

您也可以尝试以下方法(将ngOnInit()更改为async ngOnInit()

try {
  let result= await this.foodService.GetFoodPageContent(this.foodPageId).toPromise()
  // ... process result
}
catch(err) {  
  this.spinnerStatus = false;
} 
finally {
  this.spinner.hide();
}