【发布时间】:2023-03-28 13:45:01
【问题描述】:
所以,情况如下(我将简化代码,使其更具可读性,但同样的情况,我使用 json-server 将 localhost 与 Json 文件挂载):
我在 url 中有一个 json 文件(比如“http://localhost:3000”),其中包含如下信息:
{
"Object1":{
"a":"Lorem ipsum",
"b":"Dolor sit"},
"Object2":{
"a":"Amet Consectetur",
"b":"Adipiscing elit"}
}
和一个服务来获取这个数据,用一个方法改变json的对象来获取数据
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 的属性“a”,即使 url 指向 Object2。
有没有办法在进行更改后刷新视图?
【问题讨论】:
-
似乎您只是在单击按钮时才更改 URL。之后您不会尝试
get任何数据。或者,此代码中是否缺少某些内容?
标签: json angular page-refresh