簡體   English   中英

在Angular 4中顯示訂閱數據

[英]Display Subscribe Data in Angular 4

我需要幫助在Angular 4中顯示來自api的subscribe輸出。我怎么能這樣做,因為我寫了data.data.data,但它說屬性數據不存在於類型對象上。 我將如何在瀏覽器中輸出? 這是我下面的代碼和下面的api圖片

在此輸入圖像描述

import { Component, OnInit } from '@angular/core';
import { NewsService } from '../news.service';

@Component({
  selector: 'app-news-list',
  templateUrl: './news-list.component.html',
  styleUrls: ['./news-list.component.css']
})
export class NewsListComponent implements OnInit {

  constructor(private newsService: NewsService) { }

  ngOnInit() {

    this.newsService.getNews()
      .subscribe(
        data => {
          alert("News Success");
          console.log(data);
        },
        error => {
          alert("ERROR");
        });
  }
}

在組件中創建屬性

myData: any[] = [];

並在您的訂戶功能

import { Component, OnInit } from '@angular/core';
import { NewsService } from '../news.service';

@Component({
  selector: 'app-news-list',
  templateUrl: './news-list.component.html',
  styleUrls: ['./news-list.component.css']
})
export class NewsListComponent implements OnInit {

  constructor(private newsService: NewsService) { }

  ngOnInit() {

    this.newsService.getNews()
      .subscribe(
        (res: any) => {
          alert("News Success");
          this.myData = res.data; 
          // Where you find the array res.data or res.data.data
          console.log('res is ', res.data);
        },
        error => {
          alert("ERROR");
        });
      }
    }

並在您的模板中

1)查看JSON的選項

<pre>{{myData | json}}</pre>

2)如果你有數組,循環選項

<div *ngFor="let d of myData">
    {{d}}
</div>

你的數據是數組的類型,

創建任何類型的變量

myData : any;

並將數據分配給myData,

this.newsService
    .getNews()
    .subscribe(
        data => {
           this.myData = data.data;
        },
        error => {
          alert("ERROR");
        }
    );

您可以使用ngFor迭代數組並在HTML中顯示

<li *ngFor="let item of myData">
     {{item}}
</li>

你需要這樣做

ngOnInit() {
 this.newsService.getNews()
  .subscribe(
    data => {
      data = data.json();
      console.log(data.data);
    },
    error => {
      alert("ERROR");
    });

}

data.json()部分很重要,它將響應轉換為適當的json,以便訪問其數據。 現在您可以將它分配給這樣的實例變量

this.myArrayData = data.data

在你的subscribe()方法中然后在你的模板中

<div *ngFor="let data of myArrayData">
  <!-- do whatever with the data properties -->
</div>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM