![](/img/trans.png)
[英]Subscription in subscription to load data from service into component (Angular)
[英]Angular wait service subscription from component?
我在首次加載時填寫用戶自動完成時遇到問題。
這是我的UsersService
:
public users: User[] = [];
constructor(private http: HttpClient) {
this.http.get<User[]>(environment.apiUrl + URLS.USERS).subscribe({
next: (res) => {
this.Users = res;
},
error: (err) => {
console.log(err);
},
});
}
filterUsers(val: string) {
return this.users.filter(
(user) =>
user.name.toLowerCase().includes(val.toLowerCase())
);
}
我在服務構造函數上得到了Users[]
,因為this.users
將被多個組件使用。
另一方面,我有一個組件如下:
constructor(
private fb: FormBuilder,
public userService: UsersService) {
this.form = this.fb.group({
user: this.user = this.fb.control('')
});
this.filteredUsers = this.user.valueChanges.pipe(
startWith(''),
map((value: string) => this.userService.filterUsers(value))
);
}
和觀點:
<mat-form-field class="example-full-width" appearance="outline">
<mat-label>User</mat-label>
<input type="text" matInput formControlName="user" [matAutocomplete]="auto">
<mat-autocomplete autoActiveFirstOption #auto="matAutocomplete" [panelWidth]="'auto'">
<mat-option *ngFor="let sp of filteredUsers | async" [value]="sp.name">
{{sp.name}}
</mat-option>
</mat-autocomplete>
</mat-form-field>
問題:在第一次加載時, filterUsers
在 http GET 請求完成之前執行,所以this.users
為 null 並且沒有返回任何內容。 對焦時自動完成為空。
如果我輸入任何內容,那么this.users
已經具有價值並且列表會正確顯示。
如何在首次加載時設置自動完成值?
最后用 observables 解決了:
服務:
public users: User[] = [];
private subj = new BehaviorSubject('');
userObs = this.subj.asObservable();
constructor(private http: HttpClient) {
this.http.get<User[]>(environment.apiUrl + URLS.USERS).subscribe({
next: (res) => {
this.Users = res;
this.subj.next('ok');
},
error: (err) => {
console.log(err);
},
});
}
零件:
ngOnInit(): void {
this.userService.userObs.subscribe(x => { if (x == "ok") this.user.updateValueAndValidity(); });
}
而不是將 filterUsers 放入構造函數中,而是將其放入 ngOnInit。 ngOnInit 在構造函數之后調用。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.