我基本上想要创建一个自定义对话框组件,无论应用程序树中的using组件位于何处,我都可以在Angular2应用程序的任何位置使用该组件。为简单起见,我们称之为SayHello组件。
因此,我想要 SomeComponent.level3.component 来调用 SayHello.component 中的对话框。
在Angular 1.x中,我会将RootScope注入控制器并以此方式点亮对话框。现在,我了解(或多或少)对于Angular2,你可以在组件树上冒泡事件(使用事件发射器),但是从树上的SomeComponent.level3.component向下到SayHello一直冒泡一个事件似乎很乏味。 。零件。
所以我想我会创建一个SayHello服务,我会在任何想要点亮对话框的地方注入。这是我制定的代码草图。
myApp.component.ts
import {SayHelloComponent} from "<<folder>>/sayHello.component";
import {BunchOfComponents} from "<<folder>>/bunchOfComponents";
@Component({
directives: [SayHelloComponent],
selector: "my-app",
templateUrl: `<bunch-of-components>Within this component exists
SomeComponent.level3.component </bunch-of-components>
<say-hello showdialog="{{showDialog}}" message="{{message}}">
</say-hello>`
})
export class myAppComponent {
showDialog = false;
message = "";
constructor(private sayHelloService: SayHelloService) {
this.showDialog = sayHelloService.showDialog;
this.message = sayHelloService.message;
}
}
SayHelloService.ts
import {Injectable} from 'angular2/core';
@Injectable()
export class SayHelloService {
public showDialog: boolean = false;
public message: string ="";
constructor() {
}
}
SayHello.component.ts
import {Component} from "angular2/core";
import {SayHelloService} from "<<folder>>/SayHelloService";
@Component({
directives: [],
selector: "say-hello",
template: "[do hello component]"
})
export class SayHelloComponent {
@Input() showdialog: boolean;
@Input() message: string;
constructor(private sayHelloService: SayHelloService) {
}
//This idea here is to detect change in showDialog
//If true then do an alert with the message
ngOnChanges(changes: { [propName: string]: SimpleChange }) {
var obj = changes["showdialog"];
if (obj !== null) {
if (changes["showdialog"].currentValue === true) {
alert(this.message);
this.sayHelloService.showDialog = false;
}
};
}
}
SomeComponent.level3.component
import {Component} from "angular2/core";
import {SayHelloService} from "<<folder>>/SayelloService";
@Component({
directives: [],
selector: "some-component",
template: "<button (click)='doHello()'>Do say hello</button>"
})
export class PageContactUsComponent {
constructor(private sayHelloService: SayHelloService) {
}
doHello(): void {
this.sayHelloService.message = "Hello world";
this.sayHelloService.showDialog = true;
}
}
appBoot.ts
import {bootstrap} from "angular2/platform/browser";
import {MyAppComponent} from "<<folder>/MyAppComponent";
import {SayHelloService} from "<<folder>>/SayHelloService";
bootstrap(MyAppComponent, [
SayHelloService
]);
不用说,这不起作用。我没有收到任何错误,但是SayHello.component没有检测到&#39; showdialog&#39; ...值的任何变化,所以没有任何反应。关于如何正确地做到这一点的任何想法将非常感激。
答案 0 :(得分:8)
正如上面的评论所述,
要在服务中包装Observable,请参阅https://gyazo.com/cea5c4d9ff18fb93c9f47cf336942bc9。
答案 1 :(得分:1)
使用服务的替代方法是使用此处描述的ViewContainerRef / createComponent动态创建组件: