我有2个组件和1个共享服务:
父组件显示所有公司,子组件具有removeCompany方法。
问题是当我调用removeCompany方法时,来自父级的getCompanies()不会更新(如果我在父级中调用它,则removeCompany()有效);
我错过了什么?
export class CompanyService {
// Placeholder for last id so we can simulate automatic incrementing of id's
private lastId = 0;
// variable for holding companies
private companies: Company[] = [];
// URL mockup web API
private backendData = 'api/companies';
constructor ( private http: Http ) {
// Populate the companies variable on instantiation
this.http.get(this.backendData)
.map( (response: Response) => response.json().data )
.subscribe((data) => {
data.forEach(company => {
this.companies.push(company);
if (company.id > this.lastId) { this.lastId = company.id; }
});
});
}
// Simulate GET /companies
getAllcompanies(): Company[] {
return this.companies;
}
// Simulate DELETE /companies/:id
deleteCompanyById(id: number): CompanyService {
this.companies = this.companies
.filter(company => company.id !== id);
return this;
}
组件:
export class ParentComponent {
constructor(private companyService: CompanyService) {}
get companies() {
return this.companyService.getAllcompanies();
}
}
export class ChildComponent {
@Input()company: Company;
constructor(private companyService: CompanyService) {}
removeCompany(company: Company): CompanyService {
console.log(company);
return this.companyService.deleteCompanyById(company.id);
}
}
HTML
<parent *ngFor="company of companies">
<child id="child" [company]="company">
...button (click)="removeCompany(company)"....
</child>
</parent>
答案 0 :(得分:1)
问题在于,ParentComponent
不知道ChildCompany
删除了公司。要解决此问题,请在服务中使用BehaviorSubject
:
而不是
private companies: Company[] = [];
使用
private companies = new BehaviorSubject<Company[]>([]);
而不是
this.companies.push(company)
使用
this.companies.next([...this.companies.value, company]);
而不是
this.companies = this.companies
.filter(company => company.id !== id);
使用
this.companies.next(this.companies.value
.filter(company => company.id !== id));
而不是
getAllcompanies(): Company[] {
return this.companies;
}
使用
getAllcompanies(): Observable<Company[]> {
return this.companies;
}
您需要在组件内部进行订阅。
get companies() {
return this.companyService.getAllcompanies()
.subscribe(companies => this.companies = companies );
}