我有一个显示用户的组件。
users.component.ts:
dataSource!: any;
ngOnInit(): void {
this.load();
}
load(): void {
this.loading = true;
this.usersService.all()
.pipe(takeUntil(this.destroy$))
.subscribe(
(data) => {
this.loading = false;
this.dataSource = data
console.log(this.dataSource)
}, error => {
this.loading = false;
this.toastr.error(
error.error.message,
error.status + ' ' + error.statusText
);
})
}
users.component.html:
<div *ngFor="let user of dataSource">
{{user.name}}
</div>
我还有一个模式窗口,允许您添加一个新用户。
保存后,应显示新用户。
但这并没有发生。
添加组件.ts:
constructor(
public modal: NgbActiveModal,
private comp: UsersComponent
) { }
send(): void {
...
this.comp.load();
...
}
在UsersService中使用EventEmitter来通信组件:
工作堆栈litz示例
用户服务
import { EventEmitter, ... } from '@angular/core';
@Injectable()
export class UsersService {
reloadUsers = new EventEmitter<void>();
...
users.component.ts
ngOnInit() {
...
this.usersService.reloadUsers
.pipe(takeUntil(this.destroy$))
.subscribe(() => {
this.load();
});
}
添加组件.ts
send(): void {
...
this.usersService.reloadUsers.emit();
...
}