使用*ngFor,我无法从组件中获取数据。ts我component.html
同样的方法对一个类有效,但对另一个类无效。
这是我的服务类
export class FoodListService {
private url = environment.serverURL;
constructor(private http: HttpClient) {
}
//get all products from one store
getAllProducts(storeId: Number): Observable<FoodListModelServer[]> {
return this.http.get<FoodListModelServer[]>(this.url + 'foodlist/' + storeId);
}
这是我的组件类
export class FoodListComponent implements OnInit {
foodlist: FoodListModelServer[] = [];
constructor(private foodListService: FoodListService, private router: Router, private route: ActivatedRoute) {}
ngOnInit(): void {
this.foodListService.getAllProducts(this.storeId).subscribe(food => {
this.foodlist = food;
console.log(this.foodlist);
});
}
}
这是我的component.html
<div class="col-md-8 col-lg-10 col-sm-6 card">
<li *ngFor="let foodlist of foodlist">
{{foodlist.food_name}}
</li>
</div>
Console.log (this.foodlist)
I get and object{count: 5, stores: Array(5)}
为什么我得到计数包括形成一个对象,而不是仅仅数组?
如何只得到数组?
我有相同的代码与其他组件,它工作得很好。我尝试了网上提到的所有方法,但没有任何进展。
为什么我得到一个计数包括形成一个对象,而不是只是数组?
- 取决于后端API的实现
只有数组怎么走?
- 为API的实际响应创建接口,并在这里使用
this.http.get<FoodListModelServerResponse>
- 然后我们可以通过RxJs
map
算子-map(response => response.stores)
(在这里找到更多信息:https://www.learnrxjs.io/learn-rxjs/operators/transformation/map)从响应中提取值 - 就是它,您可以订阅
getAllProducts
,您将获得数组
import { map } from 'rxjs/operators';
export interface FoodListModelServerResponse {
count: number;
stores: FoodListModelServer[];
}
export class FoodListService {
private url = environment.serverURL;
constructor(private http: HttpClient) {
}
getAllProducts(storeId: Number): Observable<FoodListModelServer[]> {
return this.http.get<FoodListModelServerResponse >(this.url + 'foodlist/' + storeId)
.pipe(map(response => response.stores));
}
那么你可以使用你的实现
ngOnInit(): void {
this.foodListService.getAllProducts(this.storeId).subscribe(food => {
this.foodlist = food;
console.log(this.foodlist);
});
}
}
使用RxJs抽取操作符从响应对象中抽取stores
。将foodlist
变量声明为foodlist$: Observable<FoodListModelServer[]>
,使其可赋值给observable。
在foodService返回Observable<any>
likegetAllProducts(storeId: Number): Observable<any>
import { pluck} from 'rxjs/operators';
import { Observable } from 'rxjs';
export class FoodListComponent implements OnInit {
foodlist$: Observable<FoodListModelServer[]>;
constructor(private foodListService: FoodListService, private router: Router, private route: ActivatedRoute) {}
ngOnInit(): void {
this.foodlist$ = this.foodListService.getAllProducts(this.storeId).pipe(
pluck('stores')
);
}
}
在模板使用Async管道,它会照顾订阅和取消订阅你的foodListService.getAllProducts
<div class="col-md-8 col-lg-10 col-sm-6 card">
<li *ngFor="let foodlist of foodlist$ | async">
{{foodlist.food_name}}
</li>
</div>