bra*_*ndo 8 angular2-services angular
我基本上想要创建一个自定义对话框组件,我可以在我的Angular2应用程序中的任何位置使用它,无论应用程序树中的using组件位于何处.为简单起见,我们称之为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;
}
}
Run Code Online (Sandbox Code Playgroud)
SayHelloService.ts
import {Injectable} from 'angular2/core';
@Injectable()
export class SayHelloService {
public showDialog: boolean = false;
public message: string ="";
constructor() {
}
}
Run Code Online (Sandbox Code Playgroud)
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;
}
};
}
}
Run Code Online (Sandbox Code Playgroud)
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;
}
}
Run Code Online (Sandbox Code Playgroud)
appBoot.ts
import {bootstrap} from "angular2/platform/browser";
import {MyAppComponent} from "<<folder>/MyAppComponent";
import {SayHelloService} from "<<folder>>/SayHelloService";
bootstrap(MyAppComponent, [
SayHelloService
]);
Run Code Online (Sandbox Code Playgroud)
不用说,这不起作用.我没有得到任何错误,但SayHello.component没有检测到'showdialog'值的任何变化......所以没有任何反应.关于如何正确地做到这一点的任何想法将非常感激.