简体   繁体   English

子组件之间的 Angular 4 Master/Detail 服务通信

[英]Angular 4 Master/Detail service communication between children components

I have 2 child components within parent component, childA and childB act as master/detail.我在父组件中有 2 个子组件,childA 和 childB 充当主/细节。

在此处输入图片说明

I am using a shared service that get data from webAPI, and these children use this shared service to get the data.我正在使用从 webAPI 获取数据的共享服务,这些孩子使用此共享服务来获取数据。

api/messages - get all messages/Master api/messages - 获取所有消息/主

api/messages/1 - get 1 message with the id/Detail api/messages/1 - 获取 1 条带有 id/Detail 的消息

Child A which is master using a service to displays the list of messages in the view.使用服务在视图中显示消息列表的主节点 A。 api/messages returns all messages, each message has an id. api/messages 返回所有消息,每条消息都有一个 id。

Now when I click in the master list on the message, I am able to get the ID of the message and save it to a variable in Master component.现在,当我单击消息上的主列表时,我能够获取消息的 ID 并将其保存到主组件中的变量中。 Now the problem is how to display a message detail in detail component when message clicked in master component.现在的问题是如何在主组件中单击消息时在详细组件中显示消息详细信息。 I tried passing ID to a service but it doesn't work我尝试将 ID 传递给服务,但它不起作用

Message Service Shared:消息服务共享:

export class MessageService {

constructor(private http: HttpClient) { }

getMessages(): Observable<any> {
    return this.http.get('/api/messages').map(data => data)

}



getMessageById(): Observable<any> {
    return this.http.get('/api/messages/3' ).map(data => data) 

//the id 3 should be coming from master component and pass that id. // id 3 应该来自主组件并传递该 id。

}
}

Master component: displays list of messages in the list主组件:显示列表中的消息列表

  emails: any[];

    constructor(private messageService: MessageService) { }


  ngOnInit() {
   this.messageService.getMessages().subscribe(data => this.emails = 
   data.messages);

    }

    }

Detail components细部组件

   message;


    constructor(private messageService: MessageService) {
   }


    ngOnInit() {
    this.messageService.getMessageById().subscribe(data => this.message = 
 data);

  }

 }

you can have a @Input property in your detail component, and can change that based on what is selected in your Master component.您可以在详细信息组件中有一个@Input属性,并且可以根据在主组件中选择的内容进行更改。

something similar to below,类似于下面的东西,

 <detail [id]='<id coming from list>'></detail>

call API when ID is being set,设置ID时调用API,

private _id: string = "";
  @Input()
  get Id(): string {
    return this._id;
  }
  set Id(id: string) {
    if (this._id !== id) {
      this._id = id;

      // call API
    }
  }

now you may pass the id from master list as an event from master list component.现在您可以将主列表中的 id 作为来自主列表组件的事件传递。

An elegant solution would be to use the Subject pattern (which is a type of observable), to communicate between components and services.一个优雅的解决方案是使用主题模式(这是一种可观察的),在组件和服务之间进行通信。

Subject pattern Example:主题模式示例:

Service that handles messages:处理消息的服务:

import { Injectable } from '@angular/core';
import { Observable } from 'rxjs';
import { Subject } from 'rxjs/Subject';

@Injectable()
export class MessageService {
    private subject = new Subject<any>();

    sendMessage(message: string) {
        this.subject.next({ text: message });
    }

    clearMessage() {
        this.subject.next();
    }

    getMessage(): Observable<any> {
        return this.subject.asObservable();
    }
}

App Component that Receives Messages:接收消息的应用组件:

import { Component, OnDestroy } from '@angular/core';
import { Subscription } from 'rxjs/Subscription';

import { MessageService } from './_services/index';

@Component({
    moduleId: module.id,
    selector: 'app',
    templateUrl: 'app.component.html'
})

export class AppComponent implements OnDestroy {
    message: any;
    subscription: Subscription;

    constructor(private messageService: MessageService) {
        // subscribe to home component messages
        this.subscription = this.messageService.getMessage().subscribe(message => { this.message = message; });
    }

    ngOnDestroy() {
        // unsubscribe to ensure no memory leaks
        this.subscription.unsubscribe();
    }
}

Subjects Reference 科目参考

A more advanced pattern would be to implement Redux in your application.更高级的模式是在您的应用程序中实现Redux The key ideas of Redux are this: Redux 的核心思想是这样的:

  • All of your application's data is in a single data structure called the state - which is held in the store你的应用程序的所有数据都在一个叫做状态的单一数据结构中——它保存在存储中
  • Your app reads the state from this store您的应用程序从该商店读取状态
  • This store is never mutated directly这家商店永远不会直接变异
  • User interaction (and other code) fires actions which describe what happened用户交互(和其他代码)触发描述发生了什么的动作
  • A new state is created by combining he old state and the action by a function called the reducer.一个新的状态是通过将旧状态和一个叫做 reducer 的函数组合起来的动作来创建的。

You can read more about Redux in this detailed Redux Reference with examples你可以在这个详细的Redux Reference 中阅读更多关于 Redux 的例子

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM