1、创建服务xx.service.ts
import { Injectable } from '@angular/core';
import { Subject } from 'rxjs';
@Injectable({
providedIn: 'root'
})
export class FileCheckService {
public check$: Subject<string>;
constructor() {
this.check$ = new Subject<string>();
}
fileCheckedKeys(val: string) {
this.fileSearch$.next(val);
}
}
2、组件中 注入服务 ,调用服务传值
import { Component, OnInit, Input, Output, EventEmitter } from '@angular/core';
import { FileCheckService } from '../../../common/providers/file-check.service';
import { Subscription } from 'rxjs';
@Component({
selector: 'list-header',
templateUrl: './list-header.component.html',
styleUrls: ['./list-header.component.scss'],
})
export class ListHeaderComponent implements OnInit {
constructor(private fileCheckService: FileCheckService) {
}
ngOnInit() {
}
searchKey(val: string) {
this.fileCheckService.fileCheckedKeys(val);
}
}
3、 接收传值,并销毁Subscription
import { Component, OnInit, Input, Output, EventEmitter } from '@angular/core';
import { FileCheckService } from '../../../common/providers/file-check.service';
import { Subscription } from 'rxjs';
@Component({
selector: 'list-header',
templateUrl: './list-header.component.html',
styleUrls: ['./list-header.component.scss'],
})
export class ListHeaderComponent implements OnInit {
searchKey:string;
unSearch: Subscription;
constructor(private fileCheckService: FileCheckService) {
this.unSearch = this.fileListService.fileSearch$.subscribe(res => {
console.log(res);
});
}
ngOnInit() {
}
//销毁服务
ngOnDestroy() {
this.unSearch.unsubscribe();
}
}