我可以提供一个虚拟应用程序来演示这一点,但是可以归结为以下内容: 服务文件:dialog.service.ts
import { Injectable } from '@angular/core';
import { BehaviorSubject } from 'rxjs/BehaviorSubject';
@Injectable()
export class DialogService {
public TriggerDlgAction: BehaviorSubject<boolean>;
constructor() {
this.TriggerDlgAction = new BehaviorSubject<boolean>(false); // initialize
}
}
app.component.ts
import { Component, OnInit } from '@angular/core';
import { BehaviorSubject } from 'rxjs/BehaviorSubject';
import { DialogService } from './dialog.service';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
triggerValue: boolean = false;
constructor(private dlgSvc: DialogService ) {
}
ngOnInit() {
this.dlgSvc.TriggerDlgAction.subscribe(
(doTrigger) => {
this.triggerValue = doTrigger;
console.log(this.triggerValue);
}
)
}
}
和client.component.ts(将其模块导入到app.module.ts中。
import { Component } from '@angular/core';
import { DialogService } from '../dialog.service';
@Component({
selector: 'app-client',
templateUrl: './client.component.html',
styleUrls: ['./client.component.css']
})
export class ClientComponent {
constructor(protected dlgSvc: DialogService) { }
RequestAppFunction() {
this.dlgSvc.TriggerDlgAction<boolean>(true);
}
}
先谢谢了,:-)
答案 0 :(得分:2)
我认为问题出在您尝试仅用true
进行呼叫,因为行为主体不会期望这样被呼叫。
行为要求使用next()
调用主题,并将值传递到此处,以使它们能够发送给订阅者。
尝试修改以下代码。
import { Component } from '@angular/core';
import { DialogService } from '../dialog.service';
@Component({
selector: 'app-client',
templateUrl: './client.component.html',
styleUrls: ['./client.component.css']
})
export class ClientComponent {
constructor(protected dlgSvc: DialogService) { }
RequestAppFunction() {
this.dlgSvc.TriggerDlgAction.next(true);
^^^^^^^^^
}
}