栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

JavaScript Angular 2同级组件通信

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

JavaScript Angular 2同级组件通信

更新到rc.4: 当试图使数据在angular 2的兄弟组件之间传递时,目前最简单的方法(angular.rc.4)是利用angular2的分层依赖注入并创建共享服务。

这将是服务:

import {Injectable} from '@angular/core';@Injectable()export class SharedService {    dataArray: string[] = [];    insertData(data: string){        this.dataArray.unshift(data);    }}

现在,这里是PARENT组件

import {Component} from '@angular/core';import {SharedService} from './shared.service';import {ChildComponent} from './child.component';import {ChildSiblingComponent} from './child-sibling.component';@Component({    selector: 'parent-component',    template: `        <h1>Parent</h1>        <div> <child-component></child-component> <child-sibling-component></child-sibling-component>        </div>    `,    providers: [SharedService],    directives: [ChildComponent, ChildSiblingComponent]})export class parentComponent{} 

及其两个孩子

儿童1

import {Component, OnInit} from '@angular/core';import {SharedService} from './shared.service'@Component({    selector: 'child-component',    template: `        <h1>I am a child</h1>        <div> <ul *ngFor="#data in data">     <li>{{data}}</li> </ul>        </div>    `})export class ChildComponent implements OnInit{    data: string[] = [];    constructor(        private _sharedService: SharedService) { }    ngonInit():any {        this.data = this._sharedService.dataArray;    }}

孩子2(同级)

import {Component} from 'angular2/core';import {SharedService} from './shared.service'@Component({    selector: 'child-sibling-component',    template: `        <h1>I am a child</h1>        <input type="text" [(ngModel)]="data"/>        <button (click)="addData()"></button>    `})export class ChildSiblingComponent{    data: string = 'Testing data';    constructor(        private _sharedService: SharedService){}    addData(){        this._sharedService.insertData(this.data);        this.data = '';    }}

现在:使用此方法时要注意的事项。

  1. 仅在PARENT组件中包括共享服务的服务提供者,而不在子组件中。
  2. 你仍然必须包括构造函数并将服务导入子项中
  3. 此答案最初是针对早期的angular 2 beta版本回答的。尽管所有更改都不过是import语句,所以如果你偶然使用了原始版本,则只需更新即可。


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/371313.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号