我有两个函数,可以进行两个HTTP调用并保存从请求返回的数据。与此同时,它还将成功响应发送给从此函数返回的Subject的观察者,就像这样。
import { Observable, of, Subject} from 'rxjs';
import { first } from 'rxjs/operators';
import { HttpClient, HttpRequest } from '@angular/common/http';
export class subjectServices : : Observable<any>{
dataone : any;
constructor(private http :HttpClient)
observableOne() : Observable<any>{
let subjectone = new Subject<any>();
let subjectOneObserver = subjectOne.asObservable();
this.http.get('url').subcribe(data=>{
this.dataone = data;
subjectTwo.next("Success");
})
return subjectOneObserver;
}
observableTwo() : Observable<any>{
let subjectTwo = new Subject<any>();
let subjectTwoObserver = subjectTwo.asObservable();
this.http.get('url').subcribe(data=>{
this.dataTwo = data;
subjectTwo.next("Success");
})
return subjectTwoObserver;
}
}
在我的组件中,我想同时调用这两个函数,并等待它们都响应我使用ForkJoin这样的
import { forkJoin, Observable } from 'rxjs';
import {subjectServices} from './subjectServices.ts'
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
constructor(private SubjectServices : subjectServices){
}
callBothSubjectSimultaneously(){
let response1 = this.SubjectServices.observableOne();
let response2 = this.SubjectServices.observableTwo();
let allResponse = ForkJoin(response1, response2);
allResponse.subscribe(responseList =>{
let responseData1 = responseList[0];
let responseData2= responseList[1];
console.log("forkJoin completed")
});
}
}
尽管这两个函数都正在执行服务中的next()语句,但是allResponse.subscribe中的代码永远不会被触发。
我知道如果我直接在ForkJoin函数中提供http调用,这将起作用,但是如果可观察对象来自于我声明的主题,则它不起作用。 我不明白我在做什么错。