我使用的是Angular版本5。
我正在使用Angular-Maps从Google Places Web Service加载数据。我运行一个服务来获取数据,并将其加载到一个变量中,比如' data‘。在我的组件中,我订阅了“data”,所以每当“data”的值发生变化时,我的视图都应该更新。
但令人惊讶的是,当“数据”的值发生变化时,我可以用console.log记录这些变化,视图不会更新吗?它只在我与视图中的其他元素交互时才会更新。
这是我的服务的快照
private rs = new BehaviorSubject<Object>(undefined);
rd = this.rs.asObservable();
constructor(private mapi: MapsAPILoader)
{
this.mapsAPILoader.load().then(() =>
{
this.ps = new google.maps.places.PlacesService(document.createElement('div'));
});
}
fPi(pid: string)
{
this.ps.getDetails(
{ placeId: pid }, (pr, status) =>
{
if(status === 'OK')
{
this.extract(pr);
}
});
}
extract(pr)
{
let details = [];
if (pr.formatted_address)
{
details.push({"field": "Address", "value": placeResult.formatted_address});
}
if (pr.international_phone_number)
{
details.push({"field": "Phone Number", "value": placeResult.international_phone_number});
}
this.update(placeDetails);
}
update(rd: Object)
{
console.log(rd);
this.rs.next(rd);
}这是我的组件部分,其中是susbcribe
this.service.rd.subscribe(rd =>
{
if (rd)
this.data = Object.values(rd);
});在HTML中,我简单地做了
<div *ngIf="data">
{{data}}
</div>那么,这里出了什么问题,可以做些什么来纠正它呢?
发布于 2018-04-06 04:36:34
这是我如何在我的一个组件中处理相同类型的情况的一个示例。这里的主要内容是我创建了一个可观察对象,然后将行为的响应分配给该可观察对象。然后,我在模板中使用异步管道,它将确保所有内容都被正确取消订阅。下面是你在上面做的几乎相同的hing的例子:
import { Component, OnInit, Input, ViewChild } from '@angular/core';
import { Observable } from 'rxjs/Observable';
import { PitchingInitiativesService } from '../../services/pitching-initiatives.service';
import { EventService } from 'app/services/events/events.service';
@Component({
selector: 'app-pitching-table',
templateUrl: './pitching-table.component.html'
})
export class PitchingTableComponent implements OnInit {
@Input() searchText = '';
searchKey = 'name';
table: any = [];
constructor(
private pitching: PitchingInitiativesService,
private events: EventService
) {}
ngOnInit() {
this.pitching.getPitchingSubject();
this.pitching.pitchingResponse$.subscribe(response => this.table = response);
}
editPi(id = null) {
this.events.pitchingId(id);
}
editMilestones(id) {
this.events.milestonesId(id);
}
archivePi(id) {
this.pitching.postArchivePitch(id).subscribe(response => {
this.pitching.getPitchingSubject();
});
}
}然后在我的模板中,我使用异步管道迭代可观察对象:
<tr *ngFor="let row of table | async | filter: searchText : searchKey">我希望这能帮到你。
https://stackoverflow.com/questions/49679178
复制相似问题