这里的问题是如何从Angular 2中的服务设置输入模型值 .
这是我的示例代码:
零件:
//our root app component
import {Component} from 'angular2/core'
import {Service} from './service'
@Component({
selector: 'my-directive',
providers: [],
template: `<input [(ngModel)]="abc">`,
directives: []
})
export class Directive {
constructor(public service: Service) {
this.abc = this.service.value;
}
}
服务:
//我们的根应用程序组件从'angular2 / core'导入
@Injectable()
export class Service {
constructor() {
this.value = "service"
}
abcFun(){
// need to update value from here
}
}
2 回答
试试这个 :
component.html
component.ts
component.service.ts
问题是您在Service和Controller中有不同的值实例 . 如果在服务中更改
value
,则只更改那里的实例,控制器的实例仍然是旧实例 . 反过来也是这样 . 您可以通过将字符串存储在这样的对象中来解决此问题 .另一种解决方案是设置与observable的通信,如here所示 .