为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

慕斯王 2022-08-04 10:01:31
我完全是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.tspeople$: 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.tsgetMerchantProfile(id){    var options = this.getOptions();    return this.http.get<IMerchant[]>(environment.APIBaseURL+"/getMerchantProfile/"+id,options);}merchant.model.tsexport interface IMerchant{    email:String,    mobile : String,    password: String,    businessName : String,    otp:Number,    info:string,    url:String}
查看完整描述

2 回答

?
侃侃无极

TA贡献2051条经验 获得超10个赞

我更喜欢使用拆解方法。它不会污染数据操作的管道链,并且在处理错误后也会执行:.add()


this.userService.getMerchantsBySearch(searchTerm)

    .pipe(

        // manipulate data here

    )

    .subscribe(

        res => {

            // handle final data

        },

        error => {

            // handle error

        }

    ).add(() => {

        // teardown here (e.g. this.isLoading=false;)

    });

顺便说一句:如果 是可观察的,则无法在订阅回调内分配它。您需要将其分配给您正在使用的用户服务方法的响应。请注意不要在流上调用 subscribe,因为它将返回订阅而不是可观察量:this.people$


this.people$ = this.userService.getMerchantsBySearch(searchTerm).pipe(...)


查看完整回答
反对 回复 2022-08-04
?
开满天机

TA贡献1786条经验 获得超13个赞

你可以实际它并添加一个pipefinalize


this.userService.getMerchantsBySearch(searchTerm)

.pipe(finalize(() => this.isLoading=false))

.subscribe(

    res => {

         this.people$ =res;

    });


查看完整回答
反对 回复 2022-08-04
  • 2 回答
  • 0 关注
  • 144 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号