对于此代码:
if (!this.getItems$) {
this.getItems$ = this.httpClient
.get<Item[]>(url, options)
.pipe(shareReplay(1));
}
return this.getItems$;
这:this.httpClient.get() 是异步的。所以如果getItems$还没有设置,return语句也不会设置它。
代码按如下顺序执行:
- 1 号线。
- 2 号线和 3 号线
- 第 5 行。(返回 null)
- 第 4 行。(实际处理返回的响应)
此外,添加 if 与 shareReplay 是多余的,只有在 Observable 尚未设置时才会自动获取数据。
试试这样的:
getItems$ = this.httpClient
.get<Item[]>(url, options)
.pipe(shareReplay(1));
编辑:上面的代码是一个属性,而不是一个方法。
对于关于创建新项目的问题的第二部分,您可以执行以下操作,这是来自我的一个示例。您可以根据场景的需要重命名属性/接口。
// Action Stream
private productInsertedSubject = new Subject<Product>();
productInsertedAction$ = this.productInsertedSubject.asObservable();
// Merge the streams
productsWithAdd$ = merge(
this.productsWithCategory$, // would be your getItems$
this.productInsertedAction$
)
.pipe(
scan((acc: Product[], value: Product) => [...acc, value]),
catchError(err => {
console.error(err);
return throwError(err);
})
);
您可以在此处找到包含上述代码的完整示例:https://github.com/DeborahK/Angular-RxJS/tree/master/APM-Final
编辑:
作为参考,这里是来自 stackblitz 的关键代码:
服务
import { HttpClient } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { merge, Observable, Subject, throwError } from 'rxjs';
import { catchError, scan, shareReplay, tap } from 'rxjs/operators';
import { Item } from './item.model';
@Injectable({
providedIn: 'root'
})
export class ItemsService {
url = 'https://jsonplaceholder.typicode.com/users';
// This is a property
// It executes the http request when subscribed to the first time
// And emits the returned array of items.
// All other times, it replays (and emits) the items due to the shareReplay.
getItems$ = this.httpClient.get<Item[]>(this.url).pipe(
tap(x => console.log("I'm only getting the data once", JSON.stringify(x))),
tap(x => {
// You can write any other code here, inside the tap
// to perform any other operations
}),
shareReplay(1)
);
// Action Stream
private itemInsertedSubject = new Subject<Item>();
productInsertedAction$ = this.itemInsertedSubject.asObservable();
// Merge the action stream that emits every time an item is added
// with the data stream
allItems$ = merge(
this.getItems$,
this.productInsertedAction$
)
.pipe(
scan((acc: Item[], value: Item) => [...acc, value]),
catchError(err => {
console.error(err);
return throwError(err);
})
);
constructor(private httpClient: HttpClient) {}
addItem(item) {
this.itemInsertedSubject.next(item);
}
}
组件
import { Component, OnInit } from '@angular/core';
import { Item } from './item.model';
import { ItemsService } from './items.service';
@Component({
selector: 'app-item',
templateUrl: './item.component.html'
})
export class ItemComponent {
// Recommended technique using the async pipe in the template
// With this technique, no ngOnInit is required.
items$ = this.itemService.allItems$;
constructor(private itemService: ItemsService) {}
addItem() {
this.itemService.addItem({id: 42, name: 'Deborah Kurata'})
}
}
模板
<h1>My Component</h1>
<button (click)="addItem()">Add Item</button>
<div *ngFor="let item of items$ | async">
<div>{{item.name}}</div>
</div>