Angular 如何在角度上重新执行订阅的可观测
我有一个从API服务器获取用户列表并将其缓存的服务:Angular 如何在角度上重新执行订阅的可观测,angular,angular2-observables,Angular,Angular2 Observables,我有一个从API服务器获取用户列表并将其缓存的服务: @Injectable({ providedIn: 'root' }) export class UsersService { constructor(private apiService: ApiService) {} users: UsersListInterface[] = null; getAll():Observable<UsersListInterface[]> { if (this.us
@Injectable({
providedIn: 'root'
})
export class UsersService {
constructor(private apiService: ApiService) {}
users: UsersListInterface[] = null;
getAll():Observable<UsersListInterface[]> {
if (this.users !== null) {
return of(this.users);
}
return this.apiService.get<UsersListApiInterface[]>(16, '').pipe(
map((receivedData: UsersListApiInterface[]) => {
this.users = receivedData.map(
function(rawUser: UsersListApiInterface):UsersListInterface {
return Object.assign({}, rawUser, {
id: Number(rawUser.id)
});
}
)
return this.users;
})
);
}
add(newUser: UserVehicleDongleModel): Observable<string> {
return this.apiService.post<ResultInterface>(6, 'create', newUser).pipe(
map((receivedData: ResultInterface) => {
this.users = null;
return receivedData.result;
})
);
}
}
有没有办法在添加新用户后重新使用此订阅来提取用户列表?首先,无需手动取消订阅 其次,创建一个方法并在adduser订阅中简单地调用它
ngOnInit(): void {
this.refreshUsers();
}
private refreshUsers(): void {
this.usersService.getAll().subscribe(
((users) => {
this.users = users;
}),
((error: HttpErrorResponse) => {
console.error(error);
this.users = [];
})
)
}
onSubmit(add: NgForm) {
if (add.valid) {
if (this.selectedUser === null) {
this.addUserSubscription = this.usersService.add(newUser).subscribe(
() => {
// Refresh list of users?
this.refreshUsers();
},
(error: HttpErrorResponse) => {
console.error(error);
}
);
} else {
this.updateUserSubscription = this.usersService.update(newUser).subscribe(
() => {
//
},
(error: HttpErrorResponse) => {
console.error(error);
}
);
}
}
}
首先,没有必要手动取消订阅 其次,创建一个方法并在adduser订阅中简单地调用它
ngOnInit(): void {
this.refreshUsers();
}
private refreshUsers(): void {
this.usersService.getAll().subscribe(
((users) => {
this.users = users;
}),
((error: HttpErrorResponse) => {
console.error(error);
this.users = [];
})
)
}
onSubmit(add: NgForm) {
if (add.valid) {
if (this.selectedUser === null) {
this.addUserSubscription = this.usersService.add(newUser).subscribe(
() => {
// Refresh list of users?
this.refreshUsers();
},
(error: HttpErrorResponse) => {
console.error(error);
}
);
} else {
this.updateUserSubscription = this.usersService.update(newUser).subscribe(
() => {
//
},
(error: HttpErrorResponse) => {
console.error(error);
}
);
}
}
}
啊,我不知道Ng2会自动取消订阅http请求。这是至关重要的!谢谢啊,我不知道Ng2会自动取消订阅http请求。这是至关重要的!谢谢