首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在角9的回调中指定可观察的

在角9的回调中指定可观察的
EN

Stack Overflow用户
提问于 2020-05-06 06:25:17
回答 2查看 469关注 0票数 1

我完全是个新手。现在我被困在这里了,有些人为了让初始代码正常工作而挣扎。

用例:显示加载栏。把商人名单拿来给一个可观察的人。停止装货杆。

问题:

代码语言:javascript
复制
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调用获得响应之前就变成了假的。我知道我需要在回调中执行这个步骤,但我不知道如何执行。

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

代码语言:javascript
复制
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

代码语言:javascript
复制
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

代码语言:javascript
复制
getMerchantProfile(id){
    var options = this.getOptions();
    return this.http.get<IMerchant[]>(environment.APIBaseURL+"/getMerchantProfile/"+id,options);
}

merchant.model.ts

代码语言:javascript
复制
export interface IMerchant{
    email:String,
    mobile : String,
    password: String,
    businessName : String,
    otp:Number,
    info:string,
    url:String
}
EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2020-05-06 06:48:18

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

代码语言:javascript
复制
this.userService.getMerchantsBySearch(searchTerm)
    .pipe(
        // manipulate data here
    )
    .subscribe(
        res => {
            // handle final data
        },
        error => {
            // handle error
        }
    ).add(() => {
        // teardown here (e.g. this.isLoading=false;)
    });

顺便说一句:如果this.people$是可观察的,那么您不能在订阅回调中分配它。您需要将其分配给正在使用的userService方法的响应。注意不要在流上调用订阅,因为它将返回订阅而不是可观察到的订阅:

代码语言:javascript
复制
this.people$ = this.userService.getMerchantsBySearch(searchTerm).pipe(...)
票数 2
EN

Stack Overflow用户

发布于 2020-05-06 06:35:25

实际上,您可以pipe它并添加一个finalize

代码语言:javascript
复制
this.userService.getMerchantsBySearch(searchTerm)
.pipe(finalize(() => this.isLoading=false))
.subscribe(
    res => {
         this.people$ =res;
    });
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/61628706

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档