[英]Re-subscribe to an Angular request
我有一個父組件,它是一個表單,當我添加一個用戶時,它應該顯示在屏幕右側的一個子組件的側邊欄中。 問題是當我插入數據庫時,它不會更新用戶列表。 只有當我重新加載頁面時它才會更新。 所以我試圖重新運行 http 請求以讓用戶回來,但我沒有刷新孩子的視圖。
這是我的父組件的 HTML:
<form [formGroup]="form">
........
<button (click)="OnSubmit()" >Add User</button>
</form>
<app-sidebar [users]="users"></app-sidebar>
這是我的 TS,其中有我添加用戶的 onSubmit function:
users = [];
constructor(private userService:UserService) { }
ngOnInit(): void {
this.getUsers();
}
getUsers(){
this.userService.getUsers().subscribe(
(resp: any) => this.users = resp,
error => console.log(error)
)}
OnSubmit() {
this.userService.createUser(this.data).subscribe(
() => this.getUsers(),
(error) => console.log(error)
);
這是我的子組件的 HTML
<nav id="sidebar">
<div class="sidebar-header">
<h3>Usre</h3>
</div>
<ul *ngFor="let user of users">
<li>ID {{user.id}}</li>
<li>Name: {{user.name}}</li>
</ul>
</nav>
這就是 TS
export class SidebarComponent implements OnInit {
@Input() users;
constructor() { }
ngOnInit(): void {
}
}
在這里我也留下了我為獲取用戶所做的服務
getUsers(){
return this.http.get(`localhost:8000/users`);
}
添加用戶后,您似乎沒有將更新的用戶列表發送到子組件。 您可以在子組件中創建@Input()
屬性並從父組件發送數據:
child.component.ts:
export class ChildComponent {
//@Input() count: number;
_count: number = 0;
@Input()
set count(count: number) {
this._count = count;
console.log(count);
}
}
父.html:
<app-child [count]="counter"></app-child>
父.ts:
export class ParentComponent {
title = 'Component Interaction';
counter = 5;
increment() {
this.counter++;
}
decrement() {
this.counter--;
}
}
我會嘗試這樣的事情:
myUserService.service.ts
...
users:User[] = [];
...
getUsers(){
return (this.users)
}
addUser(user:User){
this.users.push(user)
}
...
提交
onSubmit(){
//POST request is here
this.userService.createUser(this.data).subscribe(
(resp) => {
//if POST request i susccesfull then add a user to you global users variable
if (resp.status === 'success')
myUserService.addUser(resp.user)
console.log(resp)
},
(error) => console.log(error)
);
}
子組件 HTML
<nav id="sidebar">
<div class="sidebar-header">
<h3>Usre</h3>
</div>
<ul *ngFor="let user of users">
<li>ID {{user.id}}</li>
<li>Name: {{user.name}}</li>
</ul>
</nav>
子組件.ts
...
users:User[]
constructor(private myUserService:myUserService){
this.users = myUserService.getUsers()
}
...
如果不清楚,請告訴我
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.