pass data through <router-outlet> using component interaction in angular2
Service:
import {Injectable, EventEmitter} from "@angular/core";
@Injectable()
export class DataService {
onGetData: EventEmitter = new EventEmitter();
getData() {
this.http.post(...params).map(res => {
this.onGetData.emit(res.json());
})
}
Component:
import {Component} from '@angular/core';
import {DataService} from "../services/data.service";
@Component()
export class MyComponent {
constructor(private DataService:DataService) {
this.DataService.onGetData.subscribe(res => {
(from service on .emit() )
})
}
//To send data to all subscribers from current component
sendData() {
this.DataService.onGetData.emit(--NEW DATA--);
}
}
Related videos on Youtube
Bahman Rouhani
Updated on June 04, 2022Comments
-
Bahman Rouhani almost 2 years
I'm trying to use this technique intercept input property changes with a setter to pass some data from a parent component to a child component and call a method in child component when the value is changed. my problem is the child component is binded to the parent by
<router-link>
and when I try to pass the data using:parent_component.html :
<router-outlet [some_value] = "some_value"></router-outlet>
where some_value is the parameter I am trying to pass from parent to child.
parent_component.ts :
public some_value: string;
and
parent_component.ts :
@Input() public set some_vale(number : string){ this._some_value = number; }
however I get the error
Unhandled Promise rejection: Template parse errors: Can't bind to 'some_value' since it isn't a known property of 'router-outlet'.
what am I doing wrong? What is the correct way to pass the data from parent to child component when using a
<router-outlet>
?Thanks in advance and any help appreciated.
-
Mattew Eon almost 7 yearsI think you can't do that this way. If you want to send data from the router to the child, declare a Service and use a Observable to send your object. You'll do a .next(your-object) on the component where the router is declared, and a .subscribe(object => {...}); on the child component
-