angular2 组件之间如何通过service互相传递

发布时间:2021-07-23 10:45:13 作者:小新
来源:亿速云 阅读:188

这篇文章主要介绍angular2 组件之间如何通过service互相传递,文中介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们一定要看完!

母组件传值给子组件

母组件通过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互相传递”这篇文章的所有内容,感谢各位的阅读!希望分享的内容对大家有帮助,更多相关知识,欢迎关注亿速云行业资讯频道!

推荐阅读:
  1. angular2 NgModel模块有什么用
  2. 怎么在angular2中使用NgModel模块

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

angular2 service

上一篇:MyBatis-Plus如何通过插件将数据库表生成Entiry,Mapper.xml,Mapper.class

下一篇:win10 wsl2中怎么设置redis-server开机启动

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》