[英]Angular 2 not refreshing the view after the value change of a variable?
所以,在过去的两个小时里,我一直在寻找答案。 我有一个像这样的简单AppComponent:
import {Component, OnInit} from '@angular/core';
import {UserDataService} from '../services/user-data.service';
@Component({
selector: 'myapp',
template: `
<h1>Angular 2 app inside a desktop app</h1>
<div *ngIf="data">
{{data}}
</div>
`,
})
export class AppComponent{
public data : Object;
constructor(private userDataService : UserDataService) {}
ngOnInit(){
this.data=this.userDataService.getUserData();
}
}
我想要的是从UserDataService的配置文件中导入数据,如下所示:
import {Injectable} from '@angular/core';
import {Http,Response} from '@angular/http';
import {Observable} from 'rxjs/Rx';
@Injectable()
export class UserDataService{
public data : Object;
constructor(private http : Http){}
getUserData(){
this.http.get('./config.json').map((res:Response)=>res.json())
.subscribe(data => {this.data = data});
return this.data;
}
}
我想检查该配置文件中是否存在某个变量,如果确实存在,我想显示div,但问题是视图没有像我想象的那样刷新。 我显然没有理解这种情况所以任何人都可以帮助我吗?
异步处理工作有点不同。
export class AppComponent {
public data : Object;
constructor(private userDataService : UserDataService) {}
ngOnInit() {
// subscribe and assign result when it arrives to `this.data`
this.userDataService.getUserData().subscribe(data => this.data = data);
}
}
使用.map()
而不是subscribe()
以便重新调用Observable
而不是Subscription
以允许调用者在数据到达时得到通知。
如果要在调用站点上使用结果,请添加实际return
:
getUserData() {
return this.http.get('./config.json')
.map((res:Response)=>res.json())
// .map(data => {this.data = data});
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.