简体   繁体   English

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

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

I want a service that would return the observable and set a value to field in the same method.我想要一个服务,它会返回 observable 并在同一方法中为字段设置一个值。

Now my userService.getUserDetails() method looks like this:现在我的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;
}

I want to do two things when getUserDetails is called: 1) return Observable<User> 2) set the name value so I could access it later in other classes by injecting this service in constructors, without calling the http request again.当调用getUserDetails时,我想做两件事:1)返回Observable<User> 2)设置name值,以便稍后通过在构造函数中注入此服务在其他类中访问它,而无需再次调用 http 请求。 I think I want to have something like this:我想我想要这样的东西:

  getName() {
return this.name;
 }

So I'm not sure about the subscribe, because I'm getting undefined after try to use the value.所以我不确定订阅,因为我在尝试使用该值后变得不确定。 What is the best approach here?这里最好的方法是什么?

Try to use the observable like this:尝试像这样使用 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));
    }

Ideally, this method is in a service and does nothing else but to return the observable and do error-handling if needed.理想情况下,此方法在服务中,除了返回可观察对象并在需要时进行错误处理之外什么都不做。

In your component you could have this:在您的组件中,您可以拥有以下内容:

    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.
    }
    )
    }

Alternatievly, you can also do all of this in your service, it's really your choice of design.或者,您也可以在您的服务中完成所有这些,这真的是您的设计选择。

use "tap", in your service在您的服务中使用“点击”

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

Sometimes it's used a kind of "cache"有时它被用作一种“缓存”

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

So, you always can subscribe to the function, the first time, make the call to http, the second use the value of name - of(name) return an observable因此,您始终可以订阅 function,第一次调用 http,第二次使用 name -of of(name)的值返回一个 observable

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

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