更改json数据绑定Angular 2+后刷新视图

时间:2018-02-10 20:36:00

标签: json angular page-refresh

因此,案例如下(我将简化代码,因此它更具可读性,但同样的情况,我使用json-server来安装带有Json文件的localhost):

我在网址中有一个json文件(例如“http://localhost:3000”),其中包含以下信息:

{
  "Object1":{
    "a":"Lorem ipsum",
    "b":"Dolor sit"},

  "Object2":{
    "a":"Amet Consectetur",
    "b":"Adipiscing elit"}
}

以及获取此数据的服务,其方法是更改​​json的objet以从中获取数据

getData.service.ts:

import { Injectable } from '@angular/core';
import { Http, Response } from '@angular/http';


@Injectable()
export class GetDataService {

  constructor(private http:Http) { }

  private jsonURL: string = "http://localhost:3000/Object1"

  getData() {

      return (this.http.get(this.jsonURL).map((response:Response)=>response.json()))
  }

}

  changeData(param) {
      if (param = 'Obj1'){
      this.jsonURL = "http://localhost:3000/Object1"
      }this.jsonURL = "http://localhost:3000/Object2"        
  }

}

和一个具有调用服务功能的函数的组件,如此

component1.component.ts:

import { Component, OnInit } from '@angular/core';
import { GetDataService } from './services/getData.service';

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

  data = [] 

  constructor(private getDataService: GetDataService,
              ) { }

  changeData(param) {

  this.getDataService.changeData(param)
  }

 ngOnInit() {

    const  GetDataService  = this.getDataService.getData().subscribe(data => this.data= data);

  }

和一个带有“Objetc1”绑定属性“a”的html模板,以及两个调用getDataService函数的按钮,用于更改json的对象,我将绑定数据:

component1.component.hml:

<p>{{data.a}}</p>
<button (click)="changeData('Obj1')">This button changes the url to Object1</button>
<button (click)="changeData('Obj2')">This button changes the url to Object2</button>

案例是url实际上已更改(我创建了服务的jsonURL变量的console.log()并且确实发生了更改,但是在更改之后视图未刷新并且{{data.a} }指向Object1的“a”属性,而不指向Object2的proerty“a”,即使url指向Object2。

有没有办法在进行更改后刷新视图?

1 个答案:

答案 0 :(得分:1)

<强> getData.service.ts:

...
getData() {
    return this.http.get(this.jsonURL).map(response => response.json());
}

changeData(param) {
    if (param = 'Obj1') this.jsonURL = "http://localhost:3000/Object1";
    else this.jsonURL = "http://localhost:3000/Object2";

    return this.getData();
}
...

<强> component1.component.ts:

...
data = [] 

constructor(private getDataService: GetDataService) { }

changeData(param) {
    this.getDataService.changeData(param).subscribe(res => this.data = data);
}

ngOnInit() {
    this.getDataService.getData().subscribe(data => this.data = data);
}
...