我的应用程序中有两项服务。
@Injectable()
export class SettingService {
private settings = new BehaviorSubject<any[]>([]);
constructor(private http: HttpClient) {
this.loadSettings();
}
private loadSettings() {
this.http.get<any[]>('/api/settings')
.subscribe((settings) => this.settings.next(settings));
}
getSettings() {
return this.settings.asObservable();
}
}
@Injectable()
export class InformationService {
private informations = new BehaviorSubject<any[]>([]);
constructor(private http: HttpClient) {
this.loadSettings();
}
private loadInformations(appId: string) {
this.http.get<any[]>('/api/informations/appId')
.subscribe((informations) => this.informations.next(informations));
}
getInformations(appId: string) {
return this.informations.asObservable();
}
}
我正在我的应用程序控制器中使用这些服务实例。
@Component({
selector: 'calc',
templateUrl: 'calc.component.html',
styleUrls: ['calc.component.css']
})
export class CalcComponent {
constructor(informationService: InformationService, settingsService: SettingService){
// settingsService.getSettings()
// and use settings.appId to get informations.
// informationService.getInformations(settings.appId)
}
}
如何按订单致电服务?我是rxjs的新手。
答案 0 :(得分:1)
您使用这些BehaviorSubjects的方法并不是最佳实践。
首先,删除所有类型。创建一个界面。
export interface Setting {
// whatever comes here
}
export interface Information {
// whatever comes here
}
您不需要为每个API端点提供服务,让我们在这里仅创建1。您将两个端点都包括在此服务中。他们返回了Observable。
@Injectable()
export class MyService {
constructor(private http: HttpClient) {}
public loadSettings(): Observable<Setting[]> {
return this.http.get<Setting[]>('/api/settings');
}
private loadInformations(appId: string): Observable<Information[]> {
return this.http.get<Information[]>('/api/informations/appId');
}
}
然后在您的组件中可以执行以下操作:
@Component({
selector: 'calc',
templateUrl: 'calc.component.html',
styleUrls: ['calc.component.css']
})
export class CalcComponent {
settings$: Observable<Setting[]>;
informations$: Observable<Information[]>;
constructor(private myService: MyService){
this.settings$ = myService.loadSettings();
this.informations$ = this.settings$.pipe(
switchMap(settings => myService.loadInformations(myAppId)), // whereever myAppId comes from
);
}
}
使用异步管道在模板中订阅。
答案 1 :(得分:0)
您可以使用rxjs switchMap 运算符:
settingsService.getSettings().pipe(switchMap(res1 => {
informationService.getInformations(res1.appId)
}).subscribe(res2 => {
console.log(res2)
})
答案 2 :(得分:0)
听起来您希望loadSettings
和loadInformation
的呼叫按特定顺序发生?如果您希望它们同时完成,那么我会选择forkJoin(loadSettings(), loadInformation())
,它类似于Promise.all
。如果您希望事情按一定顺序发生,那么我同意上述switchMap
的答案。我不会说上述架构不是最佳实践。这要看这里,以获取有关HTTP https://angular-academy.com/angular-architecture-best-practices/
/ Chris Noring,Angular GDE