https://gist.github.com/niniyzni/2773b28246ae629dd83b8d6aa5e57185 https://gist.github.com/niniyzni/00ed267c0cd3b97e78fd90791e54ec51
myFunc() {
console.log("function called");
// this.navItems = this.http.get("../res/data.json");
// console.log("this.navItems--->", this.navItems);
this.http
.get(
"https://cors-anywhere.herokuapp.com/http://services.groupkt.com/state/get/USA/all"
)
.subscribe(data => {
console.log("data-------->", data);
let result = data;
});
}
<div *ngFor="let r of result">
<p>{{r.id}}</p>
</div>
<ul>
<li *ngFor="let r of result">
<input type="text" name="food-name" [(ngModel)]="r.id">
</li>
</ul>
答案 0 :(得分:0)
将let result = data;
更改为this.result = data;
myFunc() {
console.log("function called");
this.http
.get(
"..." // url
)
.subscribe(data => {
console.log("data--->", data);
this.result = data;
});
}
let声明一个块范围局部变量,以访问您的类ues
this
的属性,因此this.result
如何访问您在result
模板中声明并使用的ngFor
{1}}。
答案 1 :(得分:0)
结果在myFunc
中声明和定义。所以可以尝试改为设置全局变量
export class AppComponent {
title = "Angular Coding Exercise 6";
constructor(private appService: AppService, private http: Http) {}
navItems: any;
result: any;
myFunc() {
console.log("function called");
// this.navItems = this.http.get("../res/data.json");
// console.log("this.navItems--->", this.navItems);
this.http
.get(
"https://cors-anywhere.herokuapp.com/http://services.groupkt.com/state/get/USA/all"
)
.subscribe(data => {
console.log("data-------->", data);
this.result = data;
});
}
}
答案 2 :(得分:0)
您可以尝试这样做(使用async
管道并映射结果):
import { share, map, tap } from 'rxjs/operators';
import { Observable } from 'rxjs';
...
result$: Observable<Array<any>>;
...
myFunc() {
console.log("function called");
const url = 'https://cors-anywhere.herokuapp.com/http://services.groupkt.com/state/get/USA/all';
this.result$ = this.http.get(url).pipe(
tap(_ => console.log('CHECK IF RESPONSE IS SHARED')),
map(resp => resp.RestResponse.result),
share()
);
}
您的HTML:
<div *ngFor="let r of result$ | async">
<p>{{r.id}}</p>
</div>
<ul>
<li *ngFor="let r of result$ | async">
<input type="text" name="food-name" [(ngModel)]="r.id">
</li>
</ul>
答案 3 :(得分:0)
myFunc() {
------> result : any
console.log("function called");
this.http
.get(
"https://cors-anywhere.herokuapp.com/http://services.groupkt.com/state/get/USA/all"
)
.subscribe(data => {
console.log("data-------->", data);
-----> this.result = data;
});
}