I am doing an Angular2 project with nested multiple component. I managed to send some data from immediate child component to immediate parent component. But in case of 3 nested component, how can I change or send data to multiple parent components?
For example, in following image, No 1 is message-center component. No 2 is message-list component which is called from No 1 component's html through selector < message-list [messageList]="mails" >.
No 3 is a message-detail component whose parent is No 2. Now in No 3 component if we delete one selected message from Inbox, this message will also be deleted from message-list component's which is no 2 and in No 1 component, “Deleted” labeled no will also be changed to "Deleted(1)". Now how we can change the multiple parents for a change event in 2 level nested child component which is No 3?
You can use BehaviorSubject in a service with for exemple a Message service (don't forget to add do
rxjs operator if you :
@Injectable()
export class MessageService {
public $messages: BehaviorSubject<Message[]> = new BehaviorSubject<Message[]>([]);
public getMessages() {
const url = 'your url';
return this.http.get(url).do(messages => this.$messages.next(messages));
}
}
And then to access your data in a component inject the service and use the method like :
msgService.$messages.subscribe(messages => this.messages = messages); // update data each time next is called
msgService.getMessages().subscribe(); // do the http call
then when you delete a message you just need to update the list using next :
const newList = this.messages.filter(message => message.id !== deletedMessage.id);
msgService.$messages.next(newList);
It will automaticly update the data. I hope it helps.
我已经通过调用组件3中的EventEmitter完成了通知工作。为了对组件3中的某些操作在组件1中进行操作,我通知了组件2,因为它是组件3的直接父级,并通知了其父组件1。凌乱但更容易。
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.