母组件传值给子组件
母组件通过service传值给子组件,很简单,声明一个service
@Injectable() export class ToolbarTitleService { title:string; }
然后在母组件中依赖注入
@Component({ selector: 'admin', templateUrl: './admin.component.html', styleUrls: ['./admin.component.scss'], providers: [ToolbarTitleService], })
子组件中直接声明即可使用
export class RoleListComponent implements OnInit { constructor(private toolbarTitleService:ToolbarTitleService) { console.log(this.toolbarTitleService.title); } ngOnInit() { } }
子组件传值给母组件
那么我想反过来传值回去该怎么办,即使我在子组件注入了service,母组件也不会在我修改了servie的值之后得到通知,这时候就需要用到subscribe
service代码:
import { Injectable } from '@angular/core'; import { Subject } from 'rxjs/Subject'; @Injectable() export class ToolbarTitleService { private titleSource = new Subject(); //获得一个Observable titleObservable =this.titleSource.asObservable(); constructor() { } //发射数据,当调用这个方法的时候,Subject就会发射这个数据,所有订阅了这个Subject的Subscription都会接受到结果 emitTitle(title: string) { this.titleSource.next(title); } }
子组件代码:
import { ToolbarTitleService } from './../../common/toolbar-title.service'; import { Component, OnInit ,Output,EventEmitter} from '@angular/core'; @Component({ selector: 'role-list', templateUrl: 'role-list.component.html', styleUrls: ['./role-list.component.css'], providers: [], }) export class RoleListComponent implements OnInit { constructor(private toolbarTitleService:ToolbarTitleService) { //调用方法,发射数据 this.toolbarTitleService.emitTitle('角色列表'); } ngOnInit() { } }
母组件:
import { Component, OnInit } from '@angular/core'; import { ToolbarTitleService } from "app/common/toolbar-title.service"; import { Subscription } from "rxjs/Subscription"; @Component({ selector: 'admin', templateUrl: './admin.component.html', styleUrls: ['./admin.component.scss'], providers: [ToolbarTitleService], }) export class AdminComponent implements OnInit { title: string; subscription: Subscription; constructor(private toolbarTitleService: ToolbarTitleService) { //使用subscribe来订阅,当数据被发射出来的时候,这里就会接收到结果 this.subscription = this.toolbarTitleService.titleObservable.subscribe(src => console.log('得到的title:' + src)); } ngOnInit() { } //销毁的时候需要取消订阅,因为订阅之后会一直处于观察者状态,不取消会导致泄露 ngOnDestroy() { this.subscription.unsubscribe(); } }
以上这篇angular2 组件之间通过service互相传递的实例就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持。