[英]Attach CSV data to my API JSON data in Angular application, on subscribe
[英]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.