我刚开始有角度,在试图了解自己发生了什么后,我无法想出一个解决方案。我有一个简单的模板:
<div *ngIf="allProducts$ | async as products">
<div *ngIf="products.size > 0; else noProducts">
<ul>
<li *ngFor="let product of products" >
<span>{{product.id}}</span>
<span>{{product.name}}</span>
<span (click)="productDetail(product)">Go to detail</span>
</li>
</ul>
</div>
<ng-template #noProducts>There are no products yet.</ng-template>
</div>
上课:
import {Component, OnInit} from '@angular/core';
import {Observable} from 'rxjs';
import {Product} from '../../model/product';
import {Router} from '@angular/router';
import {ProductService} from '../../service/product.service';
@Component({
selector: 'app-product-list',
templateUrl: './product-list.component.html',
styleUrls: ['./product-list.component.css']
})
export class ProductListComponent implements OnInit {
public allProducts$: Observable<Product[]>;
constructor(private router: Router,
private productService: ProductService) {}
ngOnInit() {
console.log('constructing ProductListComponent');
this.allProducts$ = this.productService.getAllProducts();
}
productDetail(product: Product) {
this.router.navigate([`product/${product.id}`]);
}
}
最后,服务:
import {Injectable} from '@angular/core';
import {HttpClient} from '@angular/common/http';
import {API_URL} from '../../app.constants';
import {Product} from '../model/product';
import {first, map} from 'rxjs/operators';
import {BehaviorSubject, Observable} from 'rxjs';
@Injectable({
providedIn: 'root'
})
export class ProductService {
constructor(private http: HttpClient) {
}
addProduct(product: Product) {
return this.http.post<Product>(`${API_URL}/product`, product, {observe: 'response'});
}
getAllProducts(): Observable<Product[]> {
return this.http.get<Product[]>(`${API_URL}/product`, {observe: 'response'})
.pipe(map(response => response.body), first());
}
}
非常简单的东西。我只是无法让它渲染。所以我尝试在服务中创建一个行为主题并将其订阅到http observable,并将其返回到组件而不是原始的http observable,认为组件可能没有及时订阅的机会,如本文所述SO。没运气。
接下来,受this SO question的启发,我尝试在订阅中手动调用markForCheck,完全删除异步管道。再一次,没有。
我无法找到任何其他解决方案,但这两个是最常见的方法,并且它似乎在任何地方工作,如here或here。为什么它对我不起作用?显然,有一些简单的事情让我不知所措。当我在订阅lambda中的控制台中记录响应主体时,我可以看到我期望从后端获得的产品实体,但是ngOnInit中的异步管道或订阅都不起作用。我也看到过使用ngZone.run的方法,但我觉得这种方法可以简单地完成与常规订阅和markForCheck相同的操作。
这看起来不正确......
<div *ngIf="products.size > 0; else noProducts">
你的意思是:
<div *ngIf="products.length > 0; else noProducts">