在 Angular 中以正确的顺序调用服务 4?
Calling services in the correct order in Angular 4?
这是我的项目布局:
这里是returns用户ID:
的用户数据服务函数
get uid(): BehaviorSubject<string> {
const uidSubject: Subject<string> = new Subject<string>();
this.afAuth.authState.subscribe((data) => {
uidSubject.next(data.uid);
});
return uidSubject;
}
然后这里是用户任务服务,它使用之前服务的 ID 获取任务:
get tasks(): BehaviorSubject<string> {
const tasksSubject: BehaviorSubject<string> = new BehaviorSubject<string>('no tasks available');
this.afs.collection(`users/${this.uid}/tasks`).valueChanges().subscribe(tasks=> {
if (tasks.length !== 0) {
tasksSubject.next(tasks);
}
});
return tasksSubject;
}
然后我在 App 组件中订阅以从任务服务获取数据,但用户 ID 显然是 undefined
因为任务函数在 uid
函数。
那么如何确保用户数据服务在调用任务服务之前获得 uid
?
我想一个解决方案是使用 Observables flatMap。
类似这样的东西(我重写了你的代码,但我无法测试它)
get uid(): BehaviorSubject<string> {
const uidSubject: Subject<string> = new Subject<string>();
return this.afAuth.authState
}
get tasks(uid): BehaviorSubject<string> {
const tasksSubject: BehaviorSubject<string> = new BehaviorSubject<string>('no tasks available');
return this.afs.collection(`users/${uid}/tasks`).valueChanges()
}
caller() {
this.uid().flatMap( data => {
//pass data as parameter, will be the id
return this.tasks(data)
})
.subscribe( tasks => {
//do what you need
})
}
关于这个
这是我的项目布局:
这里是returns用户ID:
的用户数据服务函数get uid(): BehaviorSubject<string> {
const uidSubject: Subject<string> = new Subject<string>();
this.afAuth.authState.subscribe((data) => {
uidSubject.next(data.uid);
});
return uidSubject;
}
然后这里是用户任务服务,它使用之前服务的 ID 获取任务:
get tasks(): BehaviorSubject<string> {
const tasksSubject: BehaviorSubject<string> = new BehaviorSubject<string>('no tasks available');
this.afs.collection(`users/${this.uid}/tasks`).valueChanges().subscribe(tasks=> {
if (tasks.length !== 0) {
tasksSubject.next(tasks);
}
});
return tasksSubject;
}
然后我在 App 组件中订阅以从任务服务获取数据,但用户 ID 显然是 undefined
因为任务函数在 uid
函数。
那么如何确保用户数据服务在调用任务服务之前获得 uid
?
我想一个解决方案是使用 Observables flatMap。 类似这样的东西(我重写了你的代码,但我无法测试它)
get uid(): BehaviorSubject<string> {
const uidSubject: Subject<string> = new Subject<string>();
return this.afAuth.authState
}
get tasks(uid): BehaviorSubject<string> {
const tasksSubject: BehaviorSubject<string> = new BehaviorSubject<string>('no tasks available');
return this.afs.collection(`users/${uid}/tasks`).valueChanges()
}
caller() {
this.uid().flatMap( data => {
//pass data as parameter, will be the id
return this.tasks(data)
})
.subscribe( tasks => {
//do what you need
})
}
关于这个