【问题标题】:How to Return a Observable value if its not null otherwise call an http service and return the data?如果 Observable 值不为 null,如何返回它,否则调用 http 服务并返回数据?
【发布时间】:2020-09-22 15:42:07
【问题描述】:
@Injectable()

/***
 * Service for manage profile
 */
export class ManageProfileService {

    private UserDetails: any = null;
    public GetUserDetails$: Observable<any>
}

我想从服务订阅 GetUserDetails Observable,如果 UserDetails 的值不为 null,则它应该返回,然后返回 UserDetails 变量值,否则调用 HTTP 服务“getUserDetails”并返回从服务获取的数据,如果如果 HTTP 服务失败,它应该返回 null。请任何帮助解决。

【问题讨论】:

    标签: javascript angular typescript


    【解决方案1】:

    您可以使用 RxJS of 函数将变量 UserDetails 作为 observable 返回。

    试试下面的

    服务

    import { of } from 'rxjs';
    
    @Injectable()
    export class ManageProfileService {
      private UserDetails: any = null;
    
      public getUserDetails(): Observable<any> {
        return (!!this.UserDetails) ? of(this.UserDetails) : this.http.get('url');
      }
    }
    

    然后你可以订阅组件

    组件

    export class SomeComponent implements OnInit {
      ...
    
      ngOnInit() {
        this.manageProfileService.getUserDetails().subscribe(
          res => {
            // res - `this.manageProfileService.UserDetails` if it's defined
            // res - response from `http.get('url')` if not
          },
          err => { }
        );
      }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-02-12
      • 1970-01-01
      • 2018-05-26
      • 1970-01-01
      • 2017-04-12
      • 1970-01-01
      • 2012-06-15
      • 2019-05-15
      相关资源
      最近更新 更多