简体   繁体   English

在Angular 4中的组件之间传递数据

[英]Pass data between components in Angular 4

I have list component which list Group item as table. 我有列表组件,其中列出了组项目作为表格。 One of the link is allow user to edit item. 链接之一是允许用户编辑项目。 Edit item is separate component. 编辑项目是单独的组件。 When user click on edit, i need to pass existing data to edit component. 当用户单击编辑时,我需要将现有数据传递给编辑组件。 How can i do that? 我怎样才能做到这一点?

Here is my list component 这是我的清单组件

    <div class='table-responsive'>
    <table class='table' *ngIf='groups && groups.length'>
        <thead>
            <tr>
                <th>Avatar Image</th>
                <th>Display Name</th>
                <th>Description</th>
                <th>Member Count</th>
                <th>Total Post</th>
                <th>Last Modify Date</th>
                <th></th>
            </tr>
        </thead>
        <tr *ngFor='let group of groups | groupFilter:listFilter'>
            <td><img [src]='group.group_avatar_image' class="img-responsive" style="max-height: 50px;"></td>
            <td><a [href]='group.url'>{{group.display_name}}</a></td>
            <td>{{group.description}}</td>
            <td>{{group.total_members_count}}</td>
            <td>{{group.total_posts}}</td>
            <td>{{group.updated_at | date: 'dd/MM/yyyy'}}</td>
            <td><a href="#"  [routerLink]="['/Edit Group']">Edit</a></td>
        </tr>
    </table>
</div>

Here is my list component 这是我的清单组件

 import { Component, OnInit,Input } from '@angular/core'; import { Group } from '../groupModel'; import { GroupsService } from '../groups.service'; @Component ({ selector: 'groups-lst', moduleId: module.id, templateUrl: 'groups-list.component.html' //styleUrls: ['groups.component.css'] }) export class GroupsList implements OnInit{ constructor(private _groupsService: GroupsService) {} title: string = 'Groups List'; listFilter: string = ''; errorMessage: string; groups: Group[]; ngOnInit():void{ this._groupsService.getGroups() .subscribe (group => this.groups = group, error => this.errorMessage = <any>error); } } 

There is one important thing about your approach to mention. 关于您提及的方法,有一件重要的事情。 It seems like you are thinking about a way to pass an instance of your model to the router. 似乎您正在考虑将模型实例传递给路由器的方法。 This is not possible by design (for sure, there are ways around like using a service as intermediary, but don't recommend that). 设计上不可能做到这一点(当然,有多种方法可以将服务用作中介,但不建议这样做)。

You should think about, that your records displayed within the grid might (and should) have identifiers, like an ordinary id property. 您应该考虑一下,网格中显示的记录可能(并且应该)具有标识符,例如普通的id属性。 The most common practice is to pass that identifier as parameter to the route and fetch the entity from source again. 最常见的做法是将该标识符作为参数传递给路由,然后再次从源获取实体。

Grid component: 网格组件:

<tr *ngFor='let group of groups | groupFilter:listFilter'>
   <td><img [src]='group.group_avatar_image' class="img-responsive" style="max-height: 50px;"></td>
   <td><a [href]='group.url'>{{group.display_name}}</a></td>
   <td>{{group.description}}</td>
   <td>{{group.total_members_count}}</td>
   <td>{{group.total_posts}}</td>
   <td>{{group.updated_at | date: 'dd/MM/yyyy'}}</td>
   <td><a href="#"  [routerLink]="['/Edit', group.id]">Edit</a></td>
</tr>

In your "edit component" you can use the passed parameter to fetch your group entity: 在“编辑组件”中,您可以使用传递的参数来获取组实体:

private route$ : Subscription;
constructor(private route : ActivatedRoute) {}

ngOnInit() {
   this.route$ = this.route.params.subscribe(
   (params : Params) => {
      let id = params["id"];
      // fetch the group entity from service / store
   });
}

And for sure you need to configure your route to recognize the id parameter: 并且确保您需要配置路由以识别id参数:

export const routes = [
    ...
    { path : 'Edit/:id', component : ...},
    ...
];

If components are not related by hierarchy (other than being in the same app) a service allowing subscription to a Subject is the way I usually go. 如果组件没有按层次结构关联(不是在同一个应用程序中),那么我通常会采用允许订阅主题的服务。

If components are easily related by hierarchy (parent/child), you can use Outputs. 如果组件易于按层次结构(父/子)关联,则可以使用“输出”。

Note that the service can be used for everything. 请注意,该服务可用于所有内容。 However, I typically find myself using both. 但是,我通常会同时使用两者。

There is a TON of documentation, and piles of samples, on both (some of which I've written right here on SO). 两者都有大量的文档和大量示例(我在此处已经在其中写了一些示例)。 The info you need is definitely available in a variety of questions. 您所需的信息肯定可以在各种问题中找到。 I'd be surprised if this question didn't get a dupe flag. 如果这个问题没有被骗,我会感到惊讶。

Here is a very bare-bones example of a Subject service, which you inject into any component that needs to "hear" a notification: 这是主题服务的一个非常简单的示例,您可以将其插入需要“监听”通知的任何组件中:

const Notes = {
    SOME_NAMED_EVENT : 'some_named_event',
    ... (more named events)
};

class Note {
    constructor ( name = '', data = {} ) {
        this.name = name;
        this.data = data;
    }
}

// Example of a subscription/notification style service,
// as opposed to a service that just calls a callback
class NotifierService {

    constructor() {
        let Rx = require ( 'rxjs' );
        this.subject = new Rx.Subject ( );
    }

    subscribe ( callback ) {
        return this.subject.subscribe ( b => callback ( b ) );
    }

    sendNote ( note ) {
        this.subject.next ( note );
    }
}
export { NotifierService, Notes, Note }

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

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