簡體   English   中英

如何在Angular的可觀察地圖中返回observable

[英]How to return observable in observable map in Angular

我實在找不到我想做的話。 所以我只展示自己的嘗試。這是我嘗試過的:

register(): Observable<boolean> {

   return this.registerNew().pipe(
     map(userData => {
       return this.updateProfile().pipe(                   (*1)
         map(profileData => {
           return profileData ? true : false;
         }))
     }))
}

但是,我當然會收到以下錯誤消息:

Type 'Observable<false | Observable<boolean>>' is not assignable to type 'Observable<boolean>'.

我也在考慮使用await而不是在我標記為(* 1)的行中返回。

但是,我仍然無法以一種很好的方式使其工作。

如果要從一個可觀察的對象切換到另一個可觀察的對象並使用前一個的值,則可以使用switchMap運算符

register(): Observable<boolean> {

   return this.registerNew().pipe(
     switchMap(userData => {
       return this.updateProfile().pipe(                   (*1)
         map(profileData => {
           return profileData ? true : false;
         }))
     }))
}

發生原因的原因為registerNew ,然后將結果值傳遞給switchMap返回observable(switchMap必須返回observable才能工作),然后將內部observable( updateProfile )的結果提供給訂戶。

如果要將映射的可觀測值映射到另一個可觀測值, switchMap使用mergeMapswitchMapconcatMap (取決於希望如何發射新創建的觀測值的值)。

await不是可觀察對象,僅是承諾。

當您不需要發射的值,而只想切換到另一個可觀察值時,可以使用switchMapTo()運算符。

register(): Observable<boolean> {
   return this.registerNew().pipe(
     switchMapTo(this.updateProfile()),
     map(Boolean)
   );
}

您需要concatMap

  1. 此示例僅在返回用戶ID時才要求它
  2. 第二個“ observable”使用第一個的返回值進行用戶查詢
this.authenticationService.currentUser.pipe(
    concatMap((principal: Principal) => this.getUser(principal.id))
).subscribe((user: User) => {
    console.log(user); // the user
});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM