我有2个不同的角度组件,一个用于向非实时数据库的数据库中添加数据,另一个用于检索这些数据,问题是当我想在调用saveData()时在第一个组件中添加数据时),然后将其添加到我在同一服务中调用getData()时所拥有的数据数组,然后从getData组件中调用if,然后自动显示它而无需刷新,这是我的代码:
store.service.ts:
storeChanged = new Subject<Store[]>()
baseUrl = 'MyURL';
store: Store[];
constructor(private http: HttpClient) {}
getData() {
return this.http.get<Store[]>(`${this.baseUrl}/store.php`, {
observe: 'body',
responseType: 'json'
}).subscribe((response) => {
this.store= response['data'];
})}
saveData(store) {
return this.http.post(`${this.baseUrl}/createStore.php`, store)
.subscribe((store) => {
this.store.push(store['data']);
})}
store.component.ts
subscription: Subscription;
store: Store[];
constructor(private storeService: storeService) { }
ngOnInit() {
this.storeService.getData();
}
任何帮助将不胜感激!
已编辑
addFeatures.component.ts
store: Store;
id: number;
constructor(private storeService: storeServiceService,
private route: ActivatedRoute,
private router: Router) { }
ngOnInit() {
this.route.params.subscribe(
(params: Params) =>
{
this.id = +params['id'];
this.getStoreById(this.id);
}
);
}
getStoreById = (id) => {
this.storeService.getStoreById(id).subscribe(response => this.store =
response);
}
然后使用* ngFor
将我的商店映射到模板中答案 0 :(得分:0)
您可以通过执行以下操作将store: Store[]
更改为可观察值:
store: Observable<Store[]> = this.storeChanged.asObservable();
在getData()
方法中:
...
.subscribe((response) => {
this.storeChanged.next(response['data']);
})}
在saveData()
方法中:
...
.subscribe((store) => {
this.storeChanged.next([...this.storeChanged.getValue(),store['data']]);
})}
并在 store.component.ts
中ngOnInit() {
this.storeService.store.subscribe(response => this.store = response);
this.storeService.getData();
}
希望有帮助
更新
要使用getValue()
,您需要将storeChanged
更改为BehaviorSubject
并为其传递初始值。
storeChanged: BehaviorSubject<Store[]> = new BehaviorSubject([]);
更新2
如果您要使用返回Observable
的方法来检索单个项目
getStoreByID = (id): Observable<Store> => {
return this.storeChaged.pipe(map( storeArr => storeArr.find(item => item.id === id)))
}
在组件中:
getStoreByID = (id) => {
this.storeService.getStoreByID(id).subscribe(response => this.store = response)
}