我正在使用来自 Rxjs 的 Observables 和 Subjects 在两个组件之间进行通信,这是服务部分:
import {
Injectable,
EventEmitter,
Output
} from '@angular/core';
import {
HttpClientModule,
HttpClient
} from '@angular/common/http';
import {
Observable
} from 'rxjs/Rx';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/catch';
import {
Subject
} from 'rxjs/Subject';
import {
AppConstants
} from './../config/constants';
@Injectable()
export class GlobalService {
private subject = new Subject < any > ();
@Output() LoggedIn: EventEmitter < any > = new EventEmitter();
mfaData: any;
constructor(private http: HttpClient) {
}
validateCreds(postData, institutionId, customerId) {
return this.http.post(AppConstants.baseUrl + AppConstants.serverRoutes.validateCreds + institutionId + '/' + customerId, postData)
.subscribe(response => {
console.log(response);
if (response['status'] == 203) {
this.mfaData = response['body'].questions;
if (this.mfaData[0].choices || this.mfaData[0].imageChoices) {
console.log('hey there');
this.subject.next({
mfaData: JSON.stringify(this.mfaData)
});
}
}
})
}
refreshHeaders(): Observable < any > {
return this.subject.asObservable();
}
}
import {
Subscription
} from 'rxjs/Subscription';
import {
GlobalService
} from '../../../providers/global.serivce';
export class MfaChallengeComponent implements OnInit {
subscription: Subscription;
constructor(private activatedRoute: ActivatedRoute, private bankService: BanksService, private globalService: GlobalService) {
this.subscription = this.globalService.refreshHeaders().subscribe(message => {
console.log(message);
});
}
}
但是当我从后端接收数据时,我会调用主题的下一个方法,并在另一个组件的构造函数中再次调用它。它不起作用,而我已经看到它起作用的例子。该服务已在全球范围内注入。