Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Angular 组件间通信方法总结 #60

Open
deepthan opened this issue Jun 17, 2020 · 0 comments
Open

Angular 组件间通信方法总结 #60

deepthan opened this issue Jun 17, 2020 · 0 comments

Comments

@deepthan
Copy link
Owner

deepthan commented Jun 17, 2020

1. @input@output

适用于层级较近的组件通信

父组件

...
@Component({
  selector: 'parent',
  template: `
    <son [name]="name" (sendName)="sendName($event)"></son>
  `,
})

export class ParentComponent {
    name = "momomo";
    
    sendName(newName:string){
        // newName是子组件传递回来的
    }
}

子组件

import { Component, EventEmitter, Input, Output } from '@angular/core';
@Component({
  selector: 'son',
  template: `
   <p> {{ name }} </p>
   <button (click)="modifyName()"></button>
  `,
})

export class ParentComponent {
    @Input() name:string;
    @Output() sendName = new EventEmitter<string>();
    
    modifyName(){
        this.sendName.emit('deepthan');
    }
}

==(sendName)="sendName($event)" 中 $event 是固定写法==

2. 服务

适用于层级较远的组件通信

需求:在A组件中推送数据到B组件

服务

import { Injectable } from '@angular/core';
import { Subject } from 'rxjs';

@Injectable()
export class NameService {
  name$ = new Subject<any>();

  sendName(name:string) {
    this.name$.next(name);
  }
}

A组件推数据

import { NameService } from 'xxx';
...
export class AComponent{
    constructor( private nameSrv: NameService) {
        this.nameSrv.sendName('momomo');
    }
}

B组件接收数据

import { Subscription } from 'rxjs';
import { NameService } from 'xxx';
...
export class BComponent implements OnDestroy{
    nameSub: Subscription;
    
    constructor( private nameSrv: NameService) {
        this.nameSub = this.nameSrv.name$.subscribe((name) => {
            // 接收到推送的数据
        }
    }
    
    ngOnDestroy() {
        this.nameSub.unsubscribe();
    }
}

==订阅、监听等在组件卸载的时候需要取消、删除==

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant