首先 需要创建 服务文件 ng g s server/user
user.service.ts
import { Injectable } from '@angular/core';
import { Subject, BehaviorSubject } from 'rxjs';
@Injectable({
providedIn: 'root'
})
export class UserService {
public check$: Subject<string>;
fileSearch$ = new BehaviorSubject<string>('');
constructor() {
this.check$ = new Subject<string>();
}
fileCheckedKeys(val: string) {
this.fileSearch$.next(val);
}
}
需要使用的dome.module里面引入
import { UserService } from '../../server/user.service'
providers: [UserService]
dome1.html
<app-a>
</app-a>
<app-dome2></app-dome2>
<button nz-button nzType="primary" (click)="btn2()"> 传值 </button>
dome1.ts
import { UserService } from '../../../server/user.service'
constructor(
private userService: UserService
) {
}
btn2() {
this.userService.fileCheckedKeys('这是dome1传的值');
}
app-a 路由使用
a.ts
import { Subscription } from 'rxjs';
unSearch: Subscription;
constructor(private userService: UserService) {
this.unSearch = userService.fileSearch$.subscribe(res => {
console.log(res, '这是a组件');
});
}
// 注意一定要取消订阅
ngOnDestroy() {
this.unSearch.unsubscribe();
}
app-dome2 路由使用
dome2.ts
import { Subscription } from 'rxjs';
constructor(
private userService: UserService
) {
this.unSearch = userService.fileSearch$.subscribe(res => {
console.log(res, '这是dom2组件')
})
}
unSearch: Subscription;
// 注意一定要取消订阅
ngOnDestroy() {
this.unSearch.unsubscribe();
}