如何在Angular中重新执行订阅的Observable

问题描述 投票:0回答:1

我有一个服务从API服务器获取用户列表并缓存它:

@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;
      })
    );
  }
}

此外,每次添加新用户时,都会清除缓存,因此下次组件请求用户列表时,该服务将重新查询API服务器。

我有一个使用此服务的组件,并管理一个表单来添加/编辑用户。在onInit活动中,它订阅了所有用户。它存储订阅,以便能够在ngOnDestroy事件中取消订阅:

ngOnInit(): void {
    this.getUsersSubscription = this.usersService.getAll().subscribe(
        ((users) => {
            this.users = users;
        }),
        ((error: HttpErrorResponse) => {
            console.error(error);
            this.users = [];
        })
    )
}

ngOnDestroy(): void {
    if (this.getUsersSubscription) {
        this.getUsersSubscription.unsubscribe();
    }
}

onSubmit(add: NgForm) {
    if (add.valid) {
        if (this.selectedUser === null) {
            this.addUserSubscription = this.usersService.add(newUser).subscribe(
                () => {
                    // Refresh list of users?
                },
                (error: HttpErrorResponse) => {
                    console.error(error);
                }
            );
        } else {
            this.updateUserSubscription = this.usersService.update(newUser).subscribe(
                () => {
                    //
                },
                (error: HttpErrorResponse) => {
                    console.error(error);
                }
            );
        }
    }
}

有没有办法在添加新用户后重新使用此订阅来提取用户列表?

angular angular2-observables
1个回答
1
投票

首先,没有必要手动取消订阅See this post

其次,创建一个方法,并在添加用户订阅中简单地调用它。

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);
                }
            );
        }
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.