Angular2组件间通信 [英] Angular2 component-to-component communication

查看:58
本文介绍了Angular2组件间通信的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

标题的确切含义是我的问题.我将从解释我必须做的事情开始.

exactly what the title suggests is my question. I will start by explaining what i have to do.

所以我有一个组件小部件.当我单击它时,一个包含几个项目的模式弹出窗口.每个项目代表主应用程序中的不同部分.单击任何项​​目后,将显示与该项目相关的特定部分(该部分本身就是组件).

So I have a component widget. When I click on it a modal pops containing couple of items. Each item represents a different section in the main application. On click on any item a specific section will be displayed related to that item (which is a component itself).

我没有使用Angular 1或2的预览经验,所以说实话,我不知道从哪里开始或应该搜索什么.我得出的最好结果是 EventEmitter Output Input (但这些都是我本人与孩子/父母/孩子之间的沟通所必需的)ve阅读,事实并非如此).另外,我一直在寻找 Observable ,但我认为这在这种情况下没有帮助(据我了解,我处理服务器端服务调用).如果您有任何经验,请分享.谢谢.

I have no previews experience with Angular 1 or 2 so to be honest I have no idea where to start from or what should I search for. The best I come out with is EventEmitter, Output, Input (but those are for child-parent / parent-child communication from what i've read, which is not the case). Also I've been looking on Observable but i don't think this is helpful in this situation (for what i've understand i deals with server side service calls). If you had any experience please share. Thank you.

推荐答案

下面的代码演示了在角度服务的帮助下兄弟组件,父组件和子组件之间的通信.

The code below demonstrates the communication between sibling components, parent and child components with the help of angular services.

app.module.ts

import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { FormsModule } from '@angular/forms';
import { ParentComponent } from './app.parent.component';
import { ChildComponent } from './child.component';

@NgModule({
    imports: [ BrowserModule, FormsModule ],
    declarations: [ ParentComponent, ChildComponent ],
    bootstrap: [ ParentComponent ]
})
export class AppModule {}

app.parent.component.ts

import { Component } from '@angular/core';
import { ParentChildService } from './parent-child.service';

@Component({
    selector: 'parent-app',
    template: `
        <div>
            <div>
                <h1>Hello from Parent</h1>
            </div>
            <div style="border: 1px dotted blue;">
                <p> <b> Child message history </b> </p>
                <p *ngFor="let message of childMessages">
                    {{ message }}
                </p>
            </div>
            <child-app [id] = 1> </child-app>
            <child-app [id] = 2> </child-app>
        </div>
    `,
    providers: [ ParentChildService ]
})
export class ParentComponent {
    childMessages: string[] = [];

    constructor(private parentChildService: ParentChildService) {
        parentChildService.attentionRequested$.subscribe((request) => {
            this.childMessages.push(this.parentChildService.requestedBy + ": " + request);
        });
    }
}

child.component.ts

import { Component, OnDestroy, Input } from '@angular/core';
import { ParentChildService } from './parent-child.service';
import { Subscription } from 'rxjs/Subscription';

@Component({
    selector: 'child-app',
    template: `
        <div>
            <div>
                <h2>Hello from {{ id }} child component</h2>
                <span> Message: </span> <input type="text" [(ngModel)]="message">
                <button (click) = "requestAttention();"> Request </button>
            </div>
            <div style="border: 1px dotted green;">
                <p> <b> Sibling message history </b> </p>
                <p *ngFor="let message of siblingMessages">
                    {{ message }}
                </p>
            </div>
        </div>
    `
})
export class ChildComponent implements OnDestroy {
    message: string;
    subscription: Subscription;
    siblingMessages: string[] = [];
    @Input() id: number;

    requestAttention(): void {
        this.parentChildService.requestAttention(this.message, this.id);
    }

    constructor(private parentChildService: ParentChildService) {
        this.subscription = parentChildService.attentionRequested$.subscribe((request, id) => {
            if (this.id != this.parentChildService.requestedBy) {
                this.siblingMessages.push(this.parentChildService.requestedBy + ": " + request);
            }
        });
    }

    ngOnDestroy(): void {
        // prevent memory leak when component destroyed
        this.subscription.unsubscribe();
    }
}

parent-child.service.ts

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

@Injectable()
export class ParentChildService {
    // Observable sources
    private requestAttentionSource = new Subject<string>();

    // Observable streams
    attentionRequested$ = this.requestAttentionSource.asObservable();
    requestedBy: number;

    requestAttention(request: string, id: number) {
        this.requestedBy = id;
        this.requestAttentionSource.next(request);
    }
}

要点演示了同一件事.

这篇关于Angular2组件间通信的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆