Angular:组件间通讯

121 阅读1分钟

直接调用(模版变量)

<app-modal
  (modalhandleCancel)="fatherhandleCancel($event)"
  (modalhandleOk)="fatherhandleOk($event)"
  [modalisVisible]="modalisVisible"
  [descripe]="descripe"
  #modal
>
</app-modal>
// modal就指代app-modal这个组件的实例
<button nz-button nzType="primary" nzShape="circle" (click)="modal.passvalue()">
  模版变量传值
</button>

@Input @Output

// 子组件TS
@Input() modalisVisible: boolean = false;
@Input() descripe: string = '查看';
@Input() data: object = {};
@Output() modalhandleCancel = new EventEmitter<boolean>();
@Output() modalhandleOk = new EventEmitter<boolean>();
// 父组件HTML
<app-modal
  (modalhandleCancel)="fatherhandleCancel($event)"
  (modalhandleOk)="fatherhandleOk($event)"
  [modalisVisible]="modalisVisible"
  [descripe]="descripe"
  #modal
>
</app-modal>

Service服务

如果你在根模块(一般是 app.module.ts)的 providers 里面注册一个 Service,那么这个 Service 就是全局单例的,这样一来我们就可以利用这个单例的 Service 在不同的组件之间进行通讯了。

Untitled.png

  • 比较粗暴的方式:我们可以在 Service 里面定义 public 型的共享变量,然后让不同的组件都来访问这块变量,从而达到共享数据的目的。
  • 优雅一点的方式:利用 RxJS,在 Service 里面定义一个 public 型的 Subject(主题),然后让所有组件都来 subscribe(订阅)这个主题,类似于一种“事件总线”的效果。

Cookie SessionStorage

Untitled 1.png

import { Injectable, OnInit } from '@angular/core';

@Injectable({
  providedIn: 'root',
})
export class StoreService implements OnInit {
  token: string | null = '';
  constructor() {
    this.token = sessionStorage.getItem('token');
  }
  getToken() {
    return this.token;
  }
  setToken(val: string) {
    sessionStorage.setItem('token', val);
  }
  ngOnInit() {
    // this.token = sessionStorage.getItem('token');
    // console.log(this.token);
  }
}