angular 不同组件间传递数值

利用参数订阅,将发送参数和订阅参数写成服务的形式,在需要发送数值和订阅数值的组件引入服务
发送服务和订阅服务
import { Injectable } from '@angular/core';
import { Observable } from "rxjs/Observable";
import { Subject } from "rxjs/Subject";
@Injectable()
export class CommonService {
  private subject = new Subject();
  constructor() {}
  // 发送消息
  sendInfo(count: number) {
    this.subject.next({ type: count});
  }
  // 消息监听
  getInfo(): Observable {
    return this.subject.asObservable();
  }
}

在app.module中引入服务
 providers: [..., commonService ],
在发送信息的组件中使用服务
...
import { CommonService } from '../../../../service/common.service';
...

constructor(private send: CommonService) {}
 ngOnInit(): void{
      this.send.sendMessage('44')  //传送数值 
 }

在接收信息的组件使用服务
...
import { CommonService } from '../../../../service/common.service';
...

constructor(private recive: CommonService) {}
 ngOnInit(): void{
    this.recive.getMessage().subscribe(res=>{
       console.log(res)
    })
 }

你可能感兴趣的:(angular 不同组件间传递数值)