joe*_*ter 2 json observable rxjs angular
我目前正在使用Observable在Angular 2应用程序中获取一些数据,但是我只想在请求完成后发送数据以便在我的模板中显示.我知道有使用"myValue | async"但是为了这个应用程序的目的,我需要捕获变量中的值并将该变量(带有最终值)发送到我的模板.这是我的代码
dataRetrieved() {
this._privateVariable.getData();//this subscribes to an observable
return true;//if the request was completed
}
Run Code Online (Sandbox Code Playgroud)
有没有办法做到这一点?谢谢!
更新:
谢谢您的回复.以下是我所拥有的更好的样本:
JSON:
{
"data":
{
"id" : 1,
"dataDescription": "dummy text data to save"
}
}
Run Code Online (Sandbox Code Playgroud)
HTML模板:
<div>[ngmodel] = 'myVariable' </div> <!--myVariable should contain the value of "dataDescription" from my json object. Here when I use the pipe/async instead of a variable I get an error (_myPrivateVariable.myData | async)?.dataDescription -->
Run Code Online (Sandbox Code Playgroud)
MyComponent的:
constructor (private _privateVariable: MyService){}
ngOnInit() {
this._privateVariable.getData();//this retrieves a json object, I want to be able to retrieve the value I need here instead that in the view using "| async"
Run Code Online (Sandbox Code Playgroud)
为MyService:
private _myData:BehaviorSubject<any> = new BehaviorSubject({});
public myData: Observable<any> = this._myData.asObservable();
getData (): Observable<any> {
let obs = this._http.get(URL).cache();
obs.subscribe( (response : Response) => {
let responseData = response.json();
this._myData.next(responseData.data);
});
Run Code Online (Sandbox Code Playgroud)
最后,我需要的是设置myVariable ="虚拟文本数据保存",有意义吗?
谢谢!
该async管道处理订阅你.如果您想手动进行订阅,您可以随时订阅Observable并自行处理变量的更新.
相关代码:
import {Observable} from 'rxjs/Observable';
import "rxjs/add/observable/interval";
@Component({
selector: 'my-app',
template: `
<div>
<p>Counter with async: {{ counter | async }}</p>
<p>Counter without async: {{ subscribedCounter }}</p>
</div>
`,
})
export class App {
counter: Observable<number>;
subscribedCounter: number;
constructor() {
this.counter = Observable.interval(1000);
this.counter.subscribe(
v => { this.subscribedCounter = v; }
);
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
6545 次 |
| 最近记录: |