从API获取数据并在Angular2中迭代
我是安格拉尔的新手,尝试做一项简单的任务,但似乎不起作用 这是我的TS文件从API获取数据并在Angular2中迭代,angular,angular2-routing,Angular,Angular2 Routing,我是安格拉尔的新手,尝试做一项简单的任务,但似乎不起作用 这是我的TS文件 import { Component, OnInit } from '@angular/core'; import { ApiService } from './api.service'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css'] })
import { Component, OnInit } from '@angular/core';
import { ApiService } from './api.service';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
products;
constructor(private api: ApiService) {}
ngOnInit() {
this.getProducts();
}
getProducts() {
this.products = this.api.get('http:/api/products').map((res:Response) => res.json());
console.log(this.products);
}
}
但当我尝试像这样在html文件中迭代时
<h1>Products</h1>
<div layout="row">
<!-- List the products using the class "products" -->
<div *ngFor="#product of products ; #i = index" class="products">{{ products.title }}</div>
</div>
产品
{{products.title}
没有显示输出。我的代码有什么优点?您忘记订阅observable
ngOnInit() {
this.getProducts();
}
getProducts() {
this.products = this.api.get('http:/api/products').map((res:Response) => res.json());
console.log(this.products);
}
请更改this.products=this.api.get('http:/api/products').map((res:Response)=>res.json())代码>
到
this.subscription=this.api.get('http:/api/products').map((res:Response)=>res.json()).subscription(data=>this.products=data)代码>
也可考虑改变产品的<代码>产品;I=索引<代码> >代码>产品的“大多数例子,指南使用<代码> <代码> >如果您不使用<代码> i <代码>从代码> > i =索引< /代码>代码后面请考虑删除它以保持代码更简单。
编辑:还在组件
私有订阅:订阅中添加一个新属性,并从RxJS
导入subscription
。以后不要忘记在ngondestory
或this.products=data;
之后取消订阅
假设private-api:ApiService
在内部调用http
Angular服务
或者更改模板让products of products | async
,并保持typescript代码与原始代码相同,不做任何更改。|async
将订阅可观察到的产品并自动取消订阅。{product.title}
是正确的语法,不是产品
问题在于您的可观察性
ngOnInit() {
this.getProducts();
}
getProducts() {
this.products = this.api.get('http:/api/products').map((res:Response) => res.json());
console.log(this.products);
}
需要更改为:
ngOnInit() {
this.getProducts().subscribe(data => this.products = data);
}
getProducts() {
return this.api.get('http:/api/products').map((res:Response) => res.json());
}
您的代码:
getProducts() {
this.products = this.api.get('http:/api/products').map((res:Response) => res.json());
console.log(this.products);
}
将其更改为:(无需再添加任何导入)
我收到此错误属性“subscription”在类型“AppComponent”上不存在。
请添加订阅
,正如我在产品下的回答中提到的;
行我无法添加订阅。我必须利用我写的内容。@AliRasheed:你说你必须利用你写的内容。我很好奇如果您没有导入“Response”…请参见下面的我的答案whi@AliRasheed我编辑我的答案。我假设这是一个练习/测试,您不能编辑太多。请多阅读一些官方角度文档,因为有这么简单的例子。它对您有用吗?