English 中文(简体)
不能读作未经界定的单体财产。
原标题:Cannot read property subscribe of undefined angular

我有一个服务<代码>Userservice,有办法getUsers(,这一服务由不同的单体部分分担。

这种方法称为APIC,并检索数据。 我想持有最后的APICA号呼吁的结果/状态,因此,我使用了<代码>Behavior Subject,以保持最后状态,如果不同的组成部分打电话getUsers(,则只有一份APIC号通知要求国家必须归还。

这就是我是如何执行这一决议的。

private _users$: BehaviorSubject<User[]>;

constructor(private http: HttpClient) {
    this._users$ = new BehaviorSubject([]);
}

getUsers(): BehaviorSubject<User[]> {
    if (!this._getUsersState().length) {
        this._loadUsers();
        this._users$.subscribe(() => {
            return this._users$;
        });
    } else {
        return this._users$;
    }
}

_loadUsers() {
    let _users$ = this.http.get(`${this._context}/users/`);
    _users$.subscribe((users: User[]) => {
        this._users$.next(Object.assign([], users));
    });
}

_getUsersState(): User[] {
    return this._users$.getValue();
}

构成部分

this.userService.getUsers().subscribe((users: any) => {
    console.log(users);
});

但是,我正犯以下错误:

ERROR TypeError: Cannot read property  subscribe  of undefined

如果长度为0,我就自动让用户返回。

我如何解决这一问题? 这种做法是否好?

问题回答

担任你职务:

private _users$ = new BehaviorSubject<User[]>(null);
public usersChanged = this._users$.asObservable();

constructor(private http: HttpClient) {
}

getUsers(): BehaviorSubject<User[]> {
    if (!this._getUsersState().length) {
        this._loadUsers();
        this._users$.subscribe(() => {
            return this._users$;
        });
    } else {
        return this._users$;
    }
}

_loadUsers() {
    let _users$ = this.http.get(`${this._context}/users/`);
    _users$.subscribe((users: User[]) => {
        this._users$.next(Object.assign([], users));
    });
}

_getUsersState(): User[] {
    return this._users$.getValue();
}

编辑成像:

this.userService.usersChanged
.subscribe((users: any) => {
  if(!!users){
    console.log(users);
  } else {
    console.log("No user found!");
  }
});

这是一种好的做法,它有一个可以观察到的变量: / private 行为。 因此,你只是赞同这一想法,只要国家改变,它就会消失。

getUsers method should return a observable and it s not good practice to subscribe observable in service. If you want to maintain state of users then use a singleton service. Declare property in service like this:

public users: Users[] = [];


private getUsers(): Observable<Users[]> {
 if (!this.users.length) {
   return this.http.get(`${this._context}/users/`);
 }
 return Observable.of(this.users);
}

内容提要

this.userService.getUsers().subscribe((users: User[]) => {
    this.userService.users = users; // (or users.slice(0)
    console.log(users);
});




相关问题
Angular matSort not working on Date column by desc

Trying to sort the material table with date column , date format is MM/DD/YYYY ,h:mm A , order of date is not by latest date and time. Anything which i missed from the below stackblitz code. https:/...

热门标签