【问题标题】:Getting new value from a service doesn't reload the view从服务中获取新价值不会重新加载视图
【发布时间】:2017-09-10 14:21:31
【问题描述】:

我在渲染由服务获取的数据时遇到问题。情况如下:

我有一个服务正在从一个使用 Observable 的远程 API 获得价值:

@Injectable()

export class myService {

constructor(private http: Http) { }

getData(listLength: number): Observable<Data> {
    return this.http.get(`${this.resourceUrl}/${listLength}`)
                .map((res: any) => this.convertResponse(res));
}

}

从我的服务中获取值并将它们存储在名为 data 的 var 中的组件:

@Component({
    selector: 'my-component',
    templateUrl: './my-component.component.html'
})
export class MyComponent implements OnInit{

data: Data[];

constructor(
    private myService: myService,
    private alertService: AlertService 
) {  }

loadData(length: number) {
    this.myService.getData(length).subscribe(
        (res: any) => {
            this.data= res.json();
        },
        (res: any) => this.onError(res.json())
    );
}

ngOnInit(){
    this.loadData(5);
}

private onError (error) {
    this.alertService.error(error.message, null, null);
}
}

还有一个正在渲染我的数据的视图:

<table class="table table-hover">
  <tr *ngFor="let oneData of data">
     <td>{{oneData.attr1}}</td>
     <td>{{oneData.attr2}}</td>``
  </tr>    
</table>
<button  (click)="loadData(10)">Show more</button>

问题如下:

在第一次渲染时,没有问题,数据加载良好,但是当我点击按钮时没有任何反应。但是,请求被发送到我的远程服务器。我必须再次单击,然后最终重新加载视图。

有什么想法吗?

【问题讨论】:

    标签: angular http service


    【解决方案1】:

    您是否尝试过手动触发变更检测?

    import { ChangeDetectorRef } from "@angular/core"; //<-- import
    
    constructor(
        private myService: myService,
        private alertService: AlertService,
        private changeDetector: ChangeDetectorRef //<-- inject
    ) {  }
    
    loadData(length: number) {
        this.myService.getData(length).subscribe(
            (res: any) => {
                this.data= res.json();
                this.changeDetector.detectChanges(); //<-- use
            },
            (res: any) => this.onError(res.json())
        );
    }
    

    【讨论】:

    • “对象引用没有改变” data 得到一个新值,它是唯一相关的属性。
    • @zeroflagL 你是绝对正确的。由于对象引用问题经常出现,我立即下结论。谢谢!
    猜你喜欢
    • 1970-01-01
    • 2012-02-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-05-18
    相关资源
    最近更新 更多