在我这里,UserService我有一个用户Observable对象,该对象保存已UserModel登录用户ngOnInit()的身份。为进行测试,我在登录过程中实现了该对象:
this.userService.authenticate('###', '###')
.subscribe(res => console.log('authenticated'));
Run Code Online (Sandbox Code Playgroud)
private userSource = new BehaviorSubject<UserModel>(null);
public user = this.userSource.asObservable();
Run Code Online (Sandbox Code Playgroud)
我的UserModel提供了一个称为authKey的属性,用于API身份验证。
在我ProjectService我想要做的API请求; 为此,UserModel必须存储在中的api密钥。只可能订阅用户属性,但是我读到有关避免在服务内部进行订阅的信息。
题
如何将该订阅与管道/映射连接起来?我的方法是以下代码;但这感觉像是不好的代码。
suggest(term: string): Observable<ProjectModel[]> {
return this.userSrv.user.pipe(
mergeMap((user: UserModel) => {
const options = {params: {'access-token': user.accessToken}};
return this.http.get<ProjectModel[]>(this.conf.url, options).pipe(
map(response => {
// mapping the projects ...
return projects;
})
);
})
);
}
Run Code Online (Sandbox Code Playgroud) 我曾尝试使用 Ionics 原生插件“网络”,但由于缺少提供程序而失败。为了避免任何错误,我安装了全新安装的 Ionic 和所需的依赖项:
ionic cordova plugin add cordova-plugin-network-information
npm install @ionic-native/network
Run Code Online (Sandbox Code Playgroud)
然后我将依赖添加到 home 的构造函数中:
ionic cordova plugin add cordova-plugin-network-information
npm install @ionic-native/network
Run Code Online (Sandbox Code Playgroud)
...并且在执行后会得到以下错误信息ionic serve:
ERROR Error: Uncaught (in promise):
Error: StaticInjectorError(AppModule)[HomePage -> Network]:
StaticInjectorError(Platform: core)[HomePage -> Network]:
NullInjectorError: No provider for Network!
Error: StaticInjectorError(AppModule)[HomePage -> Network]:
StaticInjectorError(Platform: core)[HomePage -> Network]:
NullInjectorError: No provider for Network!
Run Code Online (Sandbox Code Playgroud)
系统信息
Ionic:
ionic (Ionic CLI) : 4.12.0 (/Users/samnowakowski/node_modules/ionic)
Ionic Framework : @ionic/angular 4.4.0
@angular-devkit/build-angular : 0.13.9
@angular-devkit/schematics : 7.3.9
@angular/cli : …Run Code Online (Sandbox Code Playgroud)