V
V
Vladislav2017-08-03 19:47:47
Angular
Vladislav, 2017-08-03 19:47:47

Passing data between two child components in angular 2?

Good afternoon.
The second day I stick in the following problem.
How can I pass data from one child component to another? Tried through the service by subscribing. BUT due to the fact that this is an asynchronous request, the data in VIEW is not updated.
from component A I send the error code:

this._appService.onLoggerError(1);

after using the service I do emit:
onLoggerError(messageCode: number) {
this._router.navigate(['error']);
this._emmitMessageStatus.emit(messageCode)
}

and get in component B
export class AppErrorComponent implements OnInit {
public _messageErrorUser: string;
constructor(private _appService: AppService) {
}
ngOnInit() {
this._appService._emmitMessageStatus.subscribe(data => {
// date is assigned here, but outside of subscription, value is not updated
this._messageErrorUser = data;
})
// here Undefined, but it needs to be equal to data
console.log(this._messageErrorUser)
}
}

ps If possible, give an example of how to correctly transfer data from A to B through services.
Thanks

Answer the question

In order to leave comments, you need to log in

1 answer(s)
V
Vladislav, 2017-08-03
@zavvla

In general, I solved the problem through a global service. Not sure if it's correct, but it works nonetheless.
Sender:
this._appService.onLoggerError(1);
Global Service:
private __loggerSource = new BehaviorSubject(0);
__loggerError$ = this.__loggerSource.asObservable();
onLoggerError(code: number){
this.__loggerSource.next(code);
this._router.navigate(['error']);
}
Recipient:
this._subscription = this._appService.__loggerError$
.subscribe(item => {
this._messageErrorCode = item
})

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question