Angular组件通信与服务

上次我们讲完了angular自定义指令,今天就来学习一下angular是如何实现数据流动和组件通信的,当然服务也是我们要讲的一个部分。

父组件:
import { Component } from '@angular/core';

import { Hero } from './hero';

const HEROES: Hero[] = [
  { id: 11, name: 'Mr. Nice' },
  { id: 12, name: 'Narco' },
  { id: 13, name: 'Bombasto' },
  { id: 14, name: 'Celeritas' },
  { id: 15, name: 'Magneta' },
  { id: 16, name: 'RubberMan' },
  { id: 17, name: 'Dynama' },
  { id: 18, name: 'Dr IQ' },
  { id: 19, name: 'Magma' },
  { id: 20, name: 'Tornado' }
];

@Component({
  selector: 'my-app',
  template: `
    <h1>{{title}}</h1>
    <h2>My Heroes</h2>
    <ul class="heroes">
      <li *ngFor="let hero of heroes"
        [class.selected]="hero === selectedHero"
        (click)="onSelect(hero)">
        <span class="badge">{{hero.id}}</span> {{hero.name}}
      </li>
    </ul>
    <hero-detail [hero]="selectedHero"></hero-detail>
  `,
  styles: [`
    ... 此处省略
  `]
})
export class AppComponent {
  title = 'Tour of Heroes';
  heroes = HEROES;
  selectedHero: Hero;
 
 //注意ts语法规范,函数里面参数跟冒号确认参数类型,:void表示此函数无返回值
  onSelect(hero: Hero): void {
    this.selectedHero = hero;
  }
}
我们看到父组件里面有一个hero-detail子组件,有一个变量hero通过selectedHero传递,需要注意的是hero上的[]不能少,不然变量传递不到子组件。
子组件
import { Component, Input } from '@angular/core';

import { Hero } from './hero';
@Component({
  selector: 'hero-detail',
  template: `
    <div *ngIf="hero">
      <h2>{{hero.name}} details!</h2>
      <div><label>id: </label>{{hero.id}}</div>
      <div>
        <label>name: </label>
       //在这个输入框里对做修改,父组件里面hero的name不会变化,那么如何做到双向绑定,很简单
        <input value={{hero.name}} placeholder="name"/>
        <input [(ngModel)]={{hero.name}} placeholder="name"/>   用ngModel实现  
      </div>
    </div>
  `
})
export class HeroDetailComponent {
    @Input() hero: Hero;
}

在这里告诉大家一个小技巧,@ Input里面可以给参数,不给的话默认就是hero对应到父组件的hero属性。举个例子吧。。。

我把父组件里面的hero改成了herow,那么如何在子组件里面正常拿到selectedHero呢
  <hero-detail [herow]="selectedHero"></hero-detail>
子组件:
  export class HeroDetailComponent {
    @Input(‘herow’) hero: Hero;  引号不能少
 }
  这个时候的子组件的hero,就是父组件的selectedHero值

下面我们来看一下,父子组件如何实现数据通信。

// child-component.ts
import { Component, Input, Output, EventEmitter } from '@angular/core';

@Component({
    selector: 'child-component',
    template:'<div> 
            <p>{{count}}</p>
            <button (click)= ' increaseNumber'>increase</button>
            <button (click)= ' decreaseNumber'>decrease</button>
    </div>'
    ...
})
export class ChildComponent {
    @Input()
    count: number = 0;

    @Output()
    change = new EventEmitter();

    increaseNumber() {
        this.count ++;
        this.change.emit(this.count);
    }

    descreaseNumber() {
        this.count --;
        this.change.emit(this.count);
    }
}

从上述子组件的代码我们应该能够看出,这是再尝试修改count的值后,把它回传给父组件让他也更新Initialcount的值,这里有一个@Output(),change是事件触发器,并传递count的值,接下来我们看下父组件对此如何作出回应。

// father-component.ts
import { Component } from '@angular/core';
import { ChildComponent } from '../child-component/child-component';

@Component({
    template: `
        <child-component [count]='initialCount' (change)="countChange($event)"></child-component>
    `,
    ...
})
export class FatherComponent {
    initialCount: number = 5;

    countChange($event) {
          this.initialCount = $event;
    }
}
可以看出来是通过change把父子组件联系起来。

其实根本没必要这么麻烦来实现双向数据绑定,上面绕了个这么大的湾不就是想把数据双向同步。

 template: `
        <child-component [(count)]='initialCount' (change)="countChange($event)"></child-component>
    `,
简不简单,就是加了个()

既然双向数据绑定可以通过[()]来实现,那么上面的Eventemitter岂不是会显得多余,其实也不是,我们可以看下面这个例子。

// child-component.ts
@Component({
    selector: 'child-component',
    template:'<div> 
            <p>{{count}}</p>
            <button (click)= ' increaseNumber'>increase</button>
            <button (click)= ' decreaseNumber'>decrease</button>
    </div>'
    ...
})
export class ChildComponent {
    @Input()
    count: number = 0;

    @Output()
    change = new EventEmitter();

    increaseNumber() {
        this.count ++;
        if(this.count % 10 == 0)
           this.change.emit(this.count%10);
    }

    descreaseNumber() {
        this.count --;
        if(this.count % 10 == 0)
           this.change.emit(this.count%10);
    }
}

// father-component.ts
import { Component } from '@angular/core';
import { ChildComponent } from '../child-component/child-component';

@Component({
    template: `
        <p>now staged in {{count}} phase</p>
        <child-component [count]='initialCount' (change)="countChange($event)"></child-component>
    `,
    ...
})
export class FatherComponent {
    initialCount: number = 5;
    count = 1;

    countChange($event) {
          this.count = $event
    }
}

子获得父实例

从上面代码可以看出,在每次increase或decrease操作后,都会检测能否被10整除,是的话就会修改父组件的count值。下面介绍另外一种方式,在子组件中对父组件的属性作出修改。

import {Host,Component,forwardRef} from 'angular2/core';

@Component({
    selector: 'child',
    template: `
        <h2>child</h2>
    `
})
class Child {
    //使用@Host() 注入
    constructor(@Host() @Inject(forwardRef(()=> App)) app:App) {
        setInterval(()=> {
            app.i++;
        }, 1000);
    }
}

@Component({
    selector: 'App',
    template: `
        <h1>App {{i}}</h1>
        <child></child>
    `
})
export class App {
    i:number = 0;
}

父获得子实例

子元素指令在父constructor时是获取不到的,所以必须在组件的ngAfterViewInit生命周期钩子后才能获取,如果对组件生命周期不了解的话,请自行google。

import {ViewChild,Component} from 'angular2/core';

@Component({
    selector: 'child',
    template: `
        <h2>child {{i}}</h2>
    `
})
class Child {
    i:number = 0;
}

@Component({
    selector: 'App',
    directives: [Child],
    template: `
        <h1>App {{i}}</h1>
        <child></child>
    `
})
export class App {

    @ViewChild(Child) child:Child;
    ngAfterViewInit() {
        setInterval(()=> {
            this.child.i++;
        }, 1000)
    }

}

上面介绍得都是围绕父子组件的,如果不是父子而是同级组件,则如何进行通信呢,这个时候就需要引入服务了,我们先看一下什么是服务,如何使用。

//hero.service.ts 这就是一个简单的服务
import { Injectable } from '@angular/core';

import { Hero } from './hero';

const HEROES: Hero[] = [
  {id: 11, name: 'Mr. Nice'},
  {id: 12, name: 'Narco'},
  {id: 13, name: 'Bombasto'},
  {id: 14, name: 'Celeritas'},
  {id: 15, name: 'Magneta'}
];

@Injectable()
export class HeroService {
  getHeroes(): Promise<Hero[]> {
    return Promise.resolve(HEROES);
  }
}

既然我们新建了一个服务,那么怎么使用他呢?

import { Hero } from './hero';
import { HeroService } from './hero.service';

@Component({
  selector: 'my-app',
  template: `
    <h1>{{title}}</h1>
    <h2>My Heroes</h2>
    <ul class="heroes">
      <li *ngFor="let hero of heroes"
         <span class="badge">{{hero.id}}</span> {{hero.name}}
      </li>
    </ul>
    <hero-detail [hero]="selectedHero"></hero-detail>
  `,
  styles: [`
         ...
  `],
  providers: [HeroService]
})
export class AppComponent implements OnInit {
  title = 'Tour of Heroes';
  heroes: Hero[];

  constructor(private heroService: HeroService) { }
  
  //到这里就明白了服务是干嘛用的了把
  getHeroes(): void {
    this.heroService.getHeroes().then(heroes => this.heroes = heroes);
  }
 
  //组件初始化时调用方法,赋值heroes
  ngOnInit(): void {
    this.getHeroes();
  }

其实我们不难看出,一个服务就是一段通用功能的代码,里面可以很多函数供组件调用,那么服务可以作为一个中转站,联系同级组件,实现通信。具体看代码:

import {Component} from 'angular2/core';
import {HeroDetailComponent} from './hero-detail.component';
import {HeroListComponent} from './hero-list.component';

@Component({
    selector: 'my-app',
    templateUrl: 'app/template/app.html'
})
export class AppComponent {}

// app.html
<hero-list></hero-list>
<hero-detail></hero-detail>
很好,现在我们创建了这个场景,2个同级组件hero-list,hero-detail

// hero-list.component
import {Component, OnInit} from 'angular2/core';
import {Hero} from '../interface/hero';
import {HeroService} from '../service/hero.service';

@Component({
    selector: 'hero-list',
    providers: [HeroService], 
    templateUrl: 'app/template/hero-list.html',
    styleUrls: ['app/css/hero-list.css']
})
export class HeroListComponent implements OnInit {
    constructor(private _heroService: HeroService) { }

    public heroes: Hero[];
    public selectedHero: Hero;

    getHeroes() {
        this._heroService.getHeroes().then(heroes => this.heroes = heroes);
    }
    //我们想让选择英雄后,对应的hero-detail组件作出改变
    onSelect(hero: Hero) {
        //这一步就是具体的实现
        this._heroService.change(hero);
    }

    ngOnInit() {
        this.getHeroes();
    }
}

我们稍微调整一下service的代码,其实也就是加一个方法而已。

import { Injectable } from '@angular/core';
import { Hero } from './hero';

const HEROES: Hero[] = [
  {id: 11, name: 'Mr. Nice'},
  {id: 12, name: 'Narco'},
  {id: 13, name: 'Bombasto'},
  {id: 14, name: 'Celeritas'},
  {id: 15, name: 'Magneta'}
];

@Injectable()
export class HeroService {
  selectedHero:Hero;

  getHeroes(): Promise<Hero[]> {
    return Promise.resolve(HEROES);
  }
  
  //对selectedHero做出了更改
  change(hero:Hero){
    this.selectedHero = hero
}
   getHero(){
     return this.selectedHero
}
}

最后看一下hero-detail是如何写的

// hero-detail.component
import {Component} from 'angular2/core';
import {HeroService} from '../service/hero.service';

@Component({
  selector: 'hero-detail',
  templateUrl: 'app/template/hero-detail.html'
})
export class HeroDetailComponent {
  public hero: Hero;
 
  constructor(heroService:HeroService){
       this.hero = heroService.getHero()
}
}

这样就见间接实现了同级组件之间的信息传递,通过一个service完成。最后介绍一个angular里面很重要的一个东西viewChild。
ViewChild 是属性装饰器,用来从模板视图中获取匹配的元素。视图查询在 ngAfterViewInit 钩子函数调用前完成,因此在 ngAfterViewInit 钩子函数中,才能正确获取查询的元素。

import { Component, ElementRef, ViewChild, AfterViewInit } from '@angular/core';

@Component({
  selector: 'my-app',
  template: `
    <h1>Welcome to Angular World</h1>
    <p #greet>Hello {{ name }}</p>
  `,
})
export class AppComponent {
  name: string = 'Semlinker';

  @ViewChild('greet')
  greetDiv: ElementRef;

  ngAfterViewInit() {
    console.dir(this.greetDiv);
  }
}
// 其实也就是说了如何获取#greet元素

ngAfterViewInit是angular里面生命周期,在content加载完毕后调用,关于者可以参考angular文档.

@ViewChild 使用类型查询
child.component.ts
import { Component, OnInit } from '@angular/core';

@Component({
    selector: 'exe-child',
    template: `
      <p>Child Component</p>  
    `
})
export class ChildComponent {
    name: string = 'child-component';
}

import { Component, ViewChild, AfterViewInit } from '@angular/core';
import { ChildComponent } from './child.component';

app.component.ts
@Component({
  selector: 'my-app',
  template: `
    <h4>Welcome to Angular World</h4>
    <exe-child></exe-child>
  `,
})
export class AppComponent {

  @ViewChild(ChildComponent)  //用于匹配ChildComponent
  childCmp: ChildComponent;

  ngAfterViewInit() {
    console.dir(this.childCmp);
  }
}
下面是打印结果
image.png

所以可以看出childCmp是ChildComponent的一个实例,可以用childCmp.name打印出他的属性。

我们来看一下viewChildren

import { Component, ViewChildren, QueryList, AfterViewInit } from '@angular/core';
import { ChildComponent } from './child.component';

@Component({
  selector: 'my-app',
  template: `
    <h4>Welcome to Angular World</h4>
    <exe-child></exe-child>
    <exe-child></exe-child>
  `,
})
export class AppComponent {

  //由于有多个ChildComponent,所以类型是QueryList<ChildComponent>
  @ViewChildren(ChildComponent)
  childCmps: QueryList<ChildComponent>;

  ngAfterViewInit() {
    console.dir(this.childCmps);
  }
}
image.png

可见想要获取子元素可以用this.childCmps._results[index]获取。我们最后看一个官方文档给出的例子,注意指令可以写在组件里面。

import {Component, Directive, Input, ViewChild} from '@angular/core';
@Directive({selector: 'pane'})
export class Pane {
  @Input() id: string;
}
@Component({
  selector: 'example-app',
  template: `
    <pane id="1" *ngIf="shouldShow"></pane>
    <pane id="2" *ngIf="!shouldShow"></pane>
    <button (click)="toggle()">Toggle</button>
    <div>Selected: {{selectedPane}}</div> 
  `,
})
export class ViewChildComp {
  @ViewChild(Pane)
  set pane(v: Pane) {
    setTimeout(() => { this.selectedPane = v.id; }, 0);
  }
  selectedPane: string = '';
  shouldShow = true;
  toggle() { this.shouldShow = !this.shouldShow; }
}

这里可能之前没见过,在一个组件里面写指令,并把他用到component上。通过toggle方法,控制2个pane的显影。
今天就先介绍到这,下回可能带来angular的生命周期专题或者其他专题,敬请期待

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 158,233评论 4 360
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 67,013评论 1 291
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 108,030评论 0 241
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 43,827评论 0 204
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 52,221评论 3 286
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,542评论 1 216
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,814评论 2 312
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,513评论 0 198
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,225评论 1 241
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,497评论 2 244
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 31,998评论 1 258
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,342评论 2 253
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 32,986评论 3 235
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,055评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,812评论 0 194
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 35,560评论 2 271
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,461评论 2 266

推荐阅读更多精彩内容

  • Angular 2架构总览 - 简书http://www.jianshu.com/p/aeb11061b82c A...
    葡萄喃喃呓语阅读 1,435评论 2 13
  • Angular 2是一个帮助我们使用HTML和JavaScript构建客户端应用的框架。这个框架包含几个互相协作的...
    JasonQiao阅读 6,989评论 1 48
  • 组件基础 组件用来包装特定的功能,应用程序的有序运行依赖于组件之间的协同工作。组件是angular应用的最小逻辑单...
    oWSQo阅读 1,332评论 0 0
  • 版本:Angular 5.0.0-alpha AngularDart(本文档中我们通常简称 Angular ) 是...
    soojade阅读 800评论 0 4
  • 木叶有情寄明月,雄关漫道齐头越。 月若有情常相伴,风雨无摧守相望。 玲珑山水应有意,燕过无痕传真情。 江水滔滔有时...
    星月仰望阅读 227评论 0 2