简体   繁体   English

* Ngfor不显示数据

[英]*Ngfor doesnt display data

I have written a simple Angular 6 code where I am requesting data from an API with get and HTTP. 我编写了一个简单的Angular 6代码,在其中我使用get和HTTP从API请求数据。 when I run, it seems that I am getting data but *NgFor is not displaying my data. 当我运行时,似乎我正在获取数据,但是* NgFor没有显示我的数据。 I have searched many sites but since I don't get any error I can not find the problem. 我搜索了许多站点,但是由于没有任何错误,因此无法找到问题。

Below is my app.component.ts. 以下是我的app.component.ts。

    import { Component } from '@angular/core'; 
    import {HttpClient,HttpParams, HttpHeaders} from '@angular/common/http'; 
     @Component({
      selector: 'app-root', 
       templateUrl: './app.component.html',
       styleUrls: ['./app.component.css']
     })
     export class AppComponent {

       readonly ROOT_URL= 'https://api.coinmarketcap.com/v2'
       posts: any;
       data: any;

      constructor(private http:HttpClient){} 

    getPosts(){
      this.posts=this.http.get(this.ROOT_URL +'/listings').subscribe(data => { 
      console.log(data); 
      this.data = data; 
    });
      const mapped = Object.entries(this.posts).map(([type, value]) => ({type,       
    value}));

      }

      //title = 'app';
    }

Here is my app.component.html 这是我的app.component.html

    <h1>Get Cryptolist </h1> 
    <button class="btn btn-default" (click)="getPosts()">Cryptocurrency    
     list</button>
    <div class="container m-t-10" > 
    <div *ngIf = "mapped">
    <table >
     <tbody>
       <tr  *ngFor="let post of mapped">
       <td>{{post.id}}</td>
       <td>{{post.name}}</td>
       <td>{{post.symbol}}</td>
       <td>{{post.website_slug}}</td>
    </tr>
      </tbody>
    </table>
    </div>
    [enter image description here][1]</div>

Because your constant mapped is inside the scope of the function. 因为您的常量映射在函数的范围内。 Define it as the class variable and this.mapped should be inside 将其定义为类变量,this.mapped应该在内部

mapped;

getPosts(){
  this.http.get(this.ROOT_URL +'/listings').subscribe(data => { 
  console.log(data); 
  this.post = data; 
this.mapped = Object.entries(data).map(([type, value]) => ({type,       
value}));
});


  }

You are declaring mapped constant inside a function so you cannot access it in the template. 您在函数内部声明了mapped常量,因此无法在模板中访问它。 Only class level variables can be accessed in the template. 在模板中只能访问类级别的变量。 So in your app.component.ts you should create a mapped variable ie below the line data: any; 因此,在app.component.ts中,您应该在行data: any;下方创建一个mapped变量data: any; create mapped ie mapped:any; 创建映射,即mapped:any; .

And the in the function getPosts() , replace the line 然后在函数getPosts() ,替换行

const mapped = Object.entries(this.posts).map(([type, value]) => ({type,       
    value}));

with

this.mapped = Object.entries(this.posts).map(([type, value]) => ({type,       
        value}));

Also you need to move the above line inside the subscription handler of the http call ie below the line this.data = data; 另外,您还需要将上述行移动到http调用的订阅处理程序内,即this.data = data;行之下this.data = data; because it is async and this.data will be undefined if you try to access it outside the handler directly. 因为它是异步的,并且如果您尝试直接在处理程序之外访问this.data,则它将是未定义的。 Try it and it will display the data if your service is returning the data correctly. 尝试一下,如果您的服务正确返回数据,它将显示数据。 Hope it helps. 希望能帮助到你。

There are a few things that need to be done here in order to make this work properly. 为了使此工作正常进行,需要做一些事情。 One of them is to perform the data mapping within the observable stream and then bind to the correct data using the async pipe. 其中之一是在可观察流中执行数据映射,然后使用异步管道将其绑定到正确的数据。

Your controller will have this: 您的控制器将具有以下功能:

getPosts(){
  this.posts = this.http.get(this.ROOT_URL +'/listings').pipe(
    map(data => Object.entries(data))
  );
}

And in your view: 在您看来:

<tr *ngFor="let post of posts$ | async">
   <td>{{post.id}}</td>
   <td>{{post.name}}</td>
   <td>{{post.symbol}}</td>
   <td>{{post.website_slug}}</td>

Keep in mind that using object.entries will destructure your objects into an array of [key, value] pairs and cannot be used in the fashion that you have used above. 请记住,使用object.entries会将您的对象分解为[key, value]对的数组,并且不能以您上面使用的方式使用。 Simply getting rid of the map operator should fix this. 只需摆脱地图操作员即可解决此问题。

In the case someone else has the same problem, here is how I solved it. 如果有人遇到相同的问题,这就是我的解决方法。

  getPosts(){
  this.posts=this.http.get(this.ROOT_URL +'/listings').subscribe(data => { 
  console.log(data); 
  this.data = data[data];//*.NgFor could not itrate because I was itrating an 
                         //object. I needed to choose to take out element data 
                         //from the object. 
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM