【问题标题】:observables as functions or variables. angular 4 typescript作为函数或变量的可观察对象。角4打字稿
【发布时间】:2017-11-29 04:36:14
【问题描述】:

我在服务中有一个可观察的函数。

getlistofcities(){
    return this.httpclient.get(getcitylist);

我将它注入到一个组件中。

this.landingpagedependancyservice.getlistofcities()
      .subscribe(
        (city:any) =>{
          this.cities = city;
        }
      );

但是当我转到我的 ngOnDestroy() 时我注意到了

我尝试订阅我得到错误

 Property 'unsubscribe' does not exist on type 'Observable<Object>'

这让我觉得我把 observable 放在一个函数中做错了。我应该把它作为一个变量吗?

【问题讨论】:

  • 您在询问有关代码的问题,但您没有发布该代码。我们所能说的就是错误消息已经说明的内容:您试图在可观察对象上调用 unsuscribe(),而不是在订阅上调用它。订阅是 subscribe() 返回的内容。
  • 那么它应该被记录为一个变量。甜的。你回答了我的问题

标签: angular typescript observable


【解决方案1】:

你应该使用一个变量来存储subscribe的返回值,比如:

let subscription = this.landingpagedependancyservice.getlistofcities()
      .subscribe(
        (city:any) =>{
          this.cities = city;
        }
      );

然后在您的ngOnDestory 中,使用

subscription.unsubscribe()

销毁订阅。

【讨论】:

  • 你赢了一切。你的地址是什么,所以我可以把所有东西都寄到你家?
【解决方案2】:

如果你想以更灵活和可重用的方式使用它,你应该创建一个新的 Subject/Observable 并在 takeUntil 运算符中使用它

private destroy$: Subject<boolean> = new Subject<boolean>(); 

this.landingpagedependancyservice.getlistofcities()
.takeUntil(destroy$)
  .subscribe(
    (city:any) =>{
      this.cities = city;
    }
  ); 

然后在 NgDestroy 上,您应该执行以下操作:

destroy$.next(true);
destroy$.complete();

boolean 类型不是强制性的,它只是一种可能情况的示例。

【讨论】:

    【解决方案3】:

    这就是我所做的。

    来自 LandingpageDependancyService:

     getlistofcities(){
            return this.httpclient.get(getcitylist);
          }
    
        then in the landingpagecomponent:
    
    // subscription for city dependancy
     citylist : any;
    
    
    
     ngOnInit() {
         // get list of cities for city select
         this.citylist = this.landingpagedependancyservice.getlistofcities()
           .subscribe(
            (city:any) =>{
              this.cities = city;
            }
          );
      }
    
    ngOnDestroy(){
    // unsubscribe from city list
    this.citylist.unsubscribe();
    

    }

    【讨论】:

      猜你喜欢
      • 2017-10-13
      • 2019-07-04
      • 2022-07-20
      • 1970-01-01
      • 2017-01-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多