在li标签中显示数据,我正在控制台中获取数据

时间:2018-08-11 20:04:11

标签: javascript html angular angular2-template angular6

  • 我正在尝试在浏览器中显示数据
  • 当我点击api调用时,我正在控制台中获取数据。
  • 但是如何显示我的li标签中的数据。
  • 在下面提供我的相关代码,并在要点中提供整个代码

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>

4 个答案:

答案 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>

STACKBLITZ

答案 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;
      });
  }