Dan*_*Dan 9 angular2-services angular
我试图通过一个非常简单的应用程序来更好地理解服务,该应用程序获取并更新服务中的字符串值并将其显示在组件中.
这是服务:
import {Injectable} from 'angular2/core';
@Injectable()
export class SharedService {
dataString: string;
insertData(data) {
this.dataString = data
}
}
Run Code Online (Sandbox Code Playgroud)
这是主要的'app'组件:
import {Component} from 'angular2/core';
import {OtherComponent} from './other';
import {SharedService} from'./shared.service';
@Component({
selector: 'my-app',
providers: [SharedService],
directives: [OtherComponent],
template: `
<input type="text" #someValue>
<button (click)="setSharedValue(someValue.value)">Change value in shared service</button>
<br><br>
<other></other>
`
})
export class AppComponent {
constructor(private _sharedService: SharedService){}
setSharedValue(value){
this._sharedService.insertData(value);
}
}
Run Code Online (Sandbox Code Playgroud)
......这是"其他"组件:
import {Component, OnInit} from 'angular2/core';
import {SharedService} from './shared.service';
@Component({
selector : "other",
template : `
I'm the other component. The shared data is:
<p>{{data}}</p>
`,
})
export class OtherComponent implements OnInit{
data: string;
constructor(private _sharedService: SharedService){}
ngOnInit() {
this.data = this._sharedService.dataString;
}
}
Run Code Online (Sandbox Code Playgroud)
当文本添加到输入并单击按钮时,我想显示在"其他"组件中输入的值,只是为了演示获取和设置服务数据.然而,它只是默默地失败了.
谁能解释我做错了什么?
谢谢
tib*_*bus 14
您的代码是正确的,只是您的other组件不知道您更新了服务,因此它不会请求新的数据.对于这种情况,Angular2正在使用Observables:
服务 :
@Injectable()
export class SharedService {
// Observable string source
private dataStringSource = new Subject<string>();
// Observable string stream
dataString$ = this.dataStringSource.asObservable();
// Service message commands
insertData(data: string) {
this.dataStringSource.next(data)
}
}
Run Code Online (Sandbox Code Playgroud)
主要组成部分
@Component({
selector: 'my-app',
providers: [SharedService],
directives: [OtherComponent],
template: `
<input type="text" #someValue>
<button (click)="setSharedValue(someValue.value)">Change value in shared service</button>
<br><br>
<other></other>
`
})
export class AppComponent {
constructor(private _sharedService: SharedService){}
setSharedValue(value){
this._sharedService.insertData(value);
}
}
Run Code Online (Sandbox Code Playgroud)
其他组件
@Component({
selector : "other",
template : `
I'm the other component. The shared data is:
<p>{{data}}</p>
`,
})
export class OtherComponent implements OnInit{
data: string;
constructor(private _sharedService: SharedService){}
ngOnInit() {
this._sharedService.dataString$.subscribe(
data => {
this.data = data;
});
}
}
Run Code Online (Sandbox Code Playgroud)
更新的plunker可以在这里找到:https://plnkr.co/edit/neM6EdYYUkGkRpF0fKGS?p = preview
Angular2中组件之间的交互可以在这里找到:https://angular.io/docs/ts/latest/cookbook/component-communication.html#!#bidirectional-service
| 归档时间: |
|
| 查看次数: |
11594 次 |
| 最近记录: |