I am using Observables and Subjects from Rxjs to communicate between two components, Here is the service part:
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);
});
}
}
But when I receive the data from the back end I call the next method of the subject and call it again in the constructor of the other component. It doesn't work, whereas I have seen examples of it working. The service has been injected Globally.