子服务如何通知父组件更改?我曾经通过$watching (子服务中的一个变量)在角1中这样做。不幸的是,这已经不可能了。
我尝试将服务注入组件,但这失败了,可能是循环依赖造成的。根据我在当前文档中可以找到的内容,我得出了以下代码:
AppComponent
|
SomeComponent
|
SomeService
AppComponent
@Component({
selector: '[app-component]',
templateUrl: 'partials/app.html',
directives: [
SomeComponent
],
providers: [
SomeService
]
})
export class AppComponent {
constructor() { }
}
bootstrap(AppComponent);
SomeComponent
import {Component, Input} from 'angular2/core'
import {SomeService} from '../services/some.service'
@Component({
selector: 'foo',
templateUrl: 'partials/foo.html'
})
export class SomeComponent {
constructor() {}
@Input set someEvent(value) {
console.log(value);
}
}
SomeService
import {EventEmitter, Output} from 'angular2/core'
export class CoreService {
constructor() {
this.someEvent = new EventEmitter();
}
@Output() someEvent: EventEmitter<any>;
public foo() {
this.someEvent.emit(true); // Or next(true)?
}
}
发布于 2016-03-04 02:32:41
@Output
必须仅用于服务中的组件。在这个级别上,您可以使用(...)
语法注册此事件。
来自angular.io文档(https://angular.io/docs/ts/latest/api/core/Output-var.html):
声明一个事件绑定输出属性。 当输出属性发出事件时,调用附加到该事件的事件处理程序模板。
对于服务,需要在此事件上显式订阅,如下所述:
import {Component, Input} from 'angular2/core'
import {SomeService} from '../services/some.service'
@Component({
selector: 'foo',
templateUrl: 'partials/foo.html'
})
export class SomeComponent {
constructor(service:CoreService) {
service.someEvent.subscribe((val) => {
console.log(value);
});
}
}
https://stackoverflow.com/questions/35793696
复制相似问题