【问题标题】: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 => { }
);
}
}