一. 代码实现详解

子组件如果想返回去传值给父组件,父子组件相互传值需要创建service

  1. service代码
import { Injectable } from '@angular/core';
import { BehaviorSubject } from 'rxjs/BehaviorSubject';
@Injectable()
export class VideoService {
    isRecover: Boolean = false;
    isRecover$ = new BehaviorSubject<Boolean>(this.isRecover);
    
    // service定义方法 --> 子组件调用此方法传递的值,并在父组件通过subscribe去订阅传递的值
    recoverModel(status: Boolean) {  
        this.isRecover = status;
        this.isRecover$.next(this.isRecover);
    }
}
  1. 子组件调用service方法发射数据
import { VideoService } from 'app/service/video.service';
constructor(
    private videoService: VideoService
) {}
 // 子组件调用方法,发射数据'true'给父组件
 this.videoService.recoverModel(true);
  1. 父组件接收子组件传递的值
import { VideoService } from 'app/service/video.service';
constructor(
    private videoService: VideoService
) {}

ngOnInit() {
    // 父组件订阅 【isRecover$】,获取到子组件传递的值
    this.isRecoverSub = this.videoService.isRecover$.subscribe(value => {
        this.isRecover = value;
    });
}
ngOnDestroy() {
    // 销毁订阅避免内存溢出
    this.isRecoverSub.unsubscribe();
}

二. 参考链接

https://blog.csdn.net/qq16041...
https://www.cnblogs.com/yw021...


稚于最初
5 声望0 粉丝

好听的话