繁体   English   中英

以与 angular 相同的方法返回 observable 和 set 值

[英]Return observable and set value in the same method with angular

我想要一个服务,它会返回 observable 并在同一方法中为字段设置一个值。

现在我的userService.getUserDetails()方法如下所示:

private requestUrl: string;
private bic: string;
private id: string;
private name: string;

getUserDetails(): Observable<User> {
this.bic = 'aaa';
this.id= '123';

this.requestUrl = `${configs.api}v1/bics/` + encodeURIComponent(this.bic) + `/ids/` + encodeURIComponent(this.id) + `/users`;

const userObservable = this.http.get<User>(this.requestUrl).pipe(catchError(this.handleError));

userObservable.subscribe(data => this.name = data.name);

return userObservable;
}

当调用getUserDetails时,我想做两件事:1)返回Observable<User> 2)设置name值,以便稍后通过在构造函数中注入此服务在其他类中访问它,而无需再次调用 http 请求。 我想我想要这样的东西:

  getName() {
return this.name;
 }

所以我不确定订阅,因为我在尝试使用该值后变得不确定。 这里最好的方法是什么?

尝试像这样使用 observable:

   public name: string;
   public bic: string;
   public id: string;
   public getUserDetails(): Observable<User> {
        this.bic = '...';
        this.id = '...';
        this.requestUrl = `${configs.api}v1/bics/` + encodeURIComponent(this.bic) + `/ids/` + encodeURIComponent(this.id) + `/users`;

        return this.http.get<User>(this.requestUrl).pipe(catchError(this.handleError));
    }

理想情况下,此方法在服务中,除了返回可观察对象并在需要时进行错误处理之外什么都不做。

在您的组件中,您可以拥有以下内容:

    constructor(private readonly _yourService: YourService) {}

    public ngOnInit(): void {
    this.getUserDetails();
    console.log(this._yourService.name) // can be undefined, since the observable is asynchronous and probably isnt finished yet
    }

    public getUserDetails(): void{
    this._yourService.getUserDetails().subscribe(
    data => {
    this._yourService.name = data.name;
    // start doing other things, this.name should be defined, if your service returned the data correctly.
    }
    )
    }

或者,您也可以在您的服务中完成所有这些,这真的是您的设计选择。

在您的服务中使用“点击”

name:any;
const userObservable = this.http.get<User>(this.requestUrl).pipe(
tap((res)=>{
    this.name=res;
}),
catchError(this.handleError)
);

有时它被用作一种“缓存”

name:any;
const userObservable = (this.name)?of(name):
  this.http.get<User>(this.requestUrl).pipe(
    tap((res)=>{
      this.name=res;
    }),
      catchError(this.handleError)
    );

因此,您始终可以订阅 function,第一次调用 http,第二次使用 name -of of(name)的值返回一个 observable

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM