[英]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.