如何解决更新数据后,Angular不更新视图
我有两个组成部分。一种用于创建,另一种用于列出存储在数据库中的数据。 问题是,当我创建一个新数据库并存储在数据库中时,我尝试告诉“ lister”更新其视图,以便它可以显示刚刚添加的内容。奇怪的是,即使我看到它本身的数据已经从数据库中更新并加载,也没有显示出来,但没有显示该组件的视图。 在这里删除了一些代码。
“制造者”
import { Component,Inject,Input } from '@angular/core';
import { TranslateService } from '@ngx-translate/core';
import { DataService } from '../../data.service';
import { DataRestaurant } from '../../shared/data/restaurant';
import { ModulesRestaurants } from './restaurants.moldule';
@Component({
selector: 'app-module-make-restaurant',templateUrl: './make.restaurant.module.html',providers: [ModulesRestaurants]
})
export class ModulesMakeRestaurant {
@input() restaurantData = { name: '',description: '' };
restaurant: DataRestaurant;
constructor(private dataService: DataService,private translate: TranslateService,private restLister: ModulesRestaurants) {
translate.setDefaultLang('en');
}
ngOnInit() {
this.restaurant = new DataRestaurant;
}
// Create restaurant - used by the button the makes the new data
createRestaurant() {
this.dataService.createRestaurant(this.restaurantData).subscribe(data => {
this.restLister.refresh(); //Calls the 'refresh' in the lister
});
}
}
“侦听器”
import { Component,Input,Injectable,ViewChild,ApplicationRef } from '@angular/core';
import { TranslateService } from '@ngx-translate/core';
import { DataService } from '../../data.service';
import { DataRestaurant } from '../../shared/data/restaurant';
@Component({
selector: 'app-module-restaurants',templateUrl: './restaurants.module.html'
})
export class ModulesRestaurants {
@input() restaurantData = { name: '',description: '',};
DataRestaurants: any = [];
constructor(private dataService: DataService,private translate: TranslateService private appRef: ApplicationRef) {
translate.setDefaultLang('en');
}
ngOnInit() {
this.getAll();
}
refresh() {
this.getAll();
this.appRef.tick();
}
// Get all restaurants
getAll() {
return this.dataService.getAllRestaurants().subscribe((data: {}) => {
this.DataRestaurants = data;
console.log(this.DataRestaurants);
})
}
trackData(index: number,item: DataRestaurant) {
return this.DataRestaurants ? this.DataRestaurants : undefined;
}
}
数据库服务
import { Injectable } from '@angular/core';
import { HttpClient,HttpHeaders } from '@angular/common/http';
import { DataRestaurant } from '../app/shared/data/restaurant';
import { Observable,throwError } from 'rxjs';
import { retry,catchError } from 'rxjs/operators';
import { Guid } from "guid-typescript";
@Injectable({
providedIn: 'root'
})
export class DataService {
private REST_API_SERVER = "https://localhost:44377/api";
constructor(private http: HttpClient) { }
// Http Options
httpOptions = {
headers: new HttpHeaders({
'Content-Type': 'application/json'
})
}
////RESTAURANTS
//HttpClient API post() method => Get all restaurants
getAllRestaurants(): Observable<any> {
return this.http.get<DataRestaurant[]>(this.REST_API_SERVER + '/restaurant/GetAll')
.pipe(
retry(1),catchError(this.handleError<DataRestaurant[]>('getAllRestaurants'))
)
}
// HttpClient API post() method => Create restaurant
createRestaurant(data): Observable<any> {
return this.http.post<DataRestaurant>(this.REST_API_SERVER + '/restaurant/Create',JSON.stringify(data),this.httpOptions)
.pipe(
retry(1),catchError(this.handleError<DataRestaurant>('createRestaurants'))
)
}
// HttpClient API delete() method => Delete restaurant
deleteRestaurant(id): Observable<any> {
return this.http.delete<DataRestaurant>(this.REST_API_SERVER + '/restaurant/Delete/' + id,catchError(this.handleError<DataRestaurant>('deleteRestaurant'))
)
}
// Error handling
private handleError<T>(operation = 'operation',result?: T) {
return (error: any): Observable<T> => {
console.error(error);
return throwError(result as T);
};
}
}
HTML列表器
<ng-container>
<table>
<thead class="text-primary">
<tr>
<th scope="col">{{ 'restaurants.name' | translate }}</th>
<th scope="col"></th>
</tr>
</thead>
<tbody">
<tr *ngFor="let data of DataRestaurants; let i = index; trackBy: trackData" >
<td>
<input type="text"
[(ngModel)]="data.name"
class="form-control"
placeholder="Name"
style="outline:none;">
</td>
</tr>
</tbody>
</table>
<div class="row">
<div class="update">
<button type="button" class="btn btn-primary btn-round" (click)="getAll()"> Refresh </button>
</div>
</div>
</ng-container>
就像我提到的refresh()
的作品一样,它被“制造者”召唤。我什至可以看到this.DataRestaurants
已被新数据更新。但视图中未更新。
更新:
经过更多调试之后,我得出的结论似乎是同一数据有两个实例。显示的是一种,而制造商的“刷新”调用中使用了一种。 [providers]
是否与初始化时在同一线程上运行?
这里有人有建议吗?
解决方法
首先,Lister组件应仅接收餐厅数据。这提供了一个很好的智能-哑组件结构,并消除了不必要的注入。
父项
refresh$ = new Subject(); // a button can call refresh$.next() and it will retrieve the data again
restaurantData$ = this.getAll();
getAll() {
return this.refresh$.pipe(
startWith(<unknown>null),switchMap(()=> this.dataService.getAllRestaurants())
);
}
然后在模板中使用restaurantData $ |异步
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。