在 Angular 9 中的回调中分配可观察性

我完全是Angular的新手。有些人很难让初始代码工作,现在我被困在这里。

使用案例:显示加载栏。将商家列表提取到可观察对象。停止加载栏。


问题:


fetchUsers($event) {

    let searchTerm = $event.term;

    if (searchTerm.length > 3) {

      this.isLoading=true;

      this.people$ = null;

      this.userService.getMerchantsBySearch(searchTerm);

  --> this.isLoading=false;

   }

}

this.isLoading 甚至在从 getMerchantsBySearch 调用获得响应之前就变得 false。我知道我需要在回调中执行此步骤,但我不确定如何执行。


我想做这样的事情,但我错过了一些东西。正确的方法是什么。


fetchUsers($event) {

    let searchTerm = $event.term;

    if (searchTerm.length > 3) {

      this.isLoading=true;

      this.people$ = null;

      this.userService.getMerchantsBySearch(searchTerm).subscribe(

        res={

    --->  this.people$ =res;

    --->  this.isLoading=false;

        }

      );

    }

  }

dashboard.component.ts


people$: Observable<IMerchant[]>;


fetchUsers($event) {

    let searchTerm = $event.term;

    if (searchTerm.length > 3) {

      this.isLoading=true;

      this.people$ = null;

      this.userService.getMerchantsBySearch(searchTerm);

      this.isLoading=false;

    }

}

user.service.ts


getMerchantProfile(id){

    var options = this.getOptions();

    return this.http.get<IMerchant[]>(environment.APIBaseURL+"/getMerchantProfile/"+id,options);

}

merchant.model.ts


export interface IMerchant{

    email:String,

    mobile : String,

    password: String,

    businessName : String,

    otp:Number,

    info:string,

    url:String

}


慕斯王
浏览 186回答 2
2回答

侃侃无极

我更喜欢使用拆解方法。它不会污染数据操作的管道链,并且在处理错误后也会执行:.add()this.userService.getMerchantsBySearch(searchTerm)&nbsp; &nbsp; .pipe(&nbsp; &nbsp; &nbsp; &nbsp; // manipulate data here&nbsp; &nbsp; )&nbsp; &nbsp; .subscribe(&nbsp; &nbsp; &nbsp; &nbsp; res => {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; // handle final data&nbsp; &nbsp; &nbsp; &nbsp; },&nbsp; &nbsp; &nbsp; &nbsp; error => {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; // handle error&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; ).add(() => {&nbsp; &nbsp; &nbsp; &nbsp; // teardown here (e.g. this.isLoading=false;)&nbsp; &nbsp; });顺便说一句:如果 是可观察的,则无法在订阅回调内分配它。您需要将其分配给您正在使用的用户服务方法的响应。请注意不要在流上调用 subscribe,因为它将返回订阅而不是可观察量:this.people$this.people$ = this.userService.getMerchantsBySearch(searchTerm).pipe(...)

开满天机

你可以实际它并添加一个pipefinalizethis.userService.getMerchantsBySearch(searchTerm).pipe(finalize(() => this.isLoading=false)).subscribe(&nbsp; &nbsp; res => {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;this.people$ =res;&nbsp; &nbsp; });
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript