首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >Angular BehaviorSubject和Output

Angular BehaviorSubject和Output
EN

Stack Overflow用户
提问于 2021-02-21 19:29:25
回答 1查看 151关注 0票数 0

在我的应用程序中,我使用behavior subject来加载数据:

我的服务:

代码语言:javascript
运行
复制
  data$ = new BehaviorSubject({
      users: [],
      user: {}
  });

  constructor(​​);

  }​​
  
  dispatch(action: Action): Observable<true | { error: string; }> {
      switch (action.type) {
          case ActionTypes.USER_LIST:
              this.getUsers();
              return of(true);
          default:
              return of(true);
      }
  }

  private getUsers(){
      this.http.get("url")
      .subscribe((users: any) => {
          this.data$.next({...this.data$.value, users: users});
      });
  }

当子组件请求此服务时,我会在父组件中调用此服务。

MyParentComponent:

代码语言:javascript
运行
复制
export class MyParentComponent implements OnInit {
  isLoading = false;
  user$ = new BehaviorSubject(null);

  constructor(private userService: UserService) { }

  ngOnInit(): void {
    
  }
  
  getUsers(event) {
    this.isLoading = true;
    this.userService.dispatch({type: Action Types.USERR_LIST});
    this.user$.next(this.userService.data$);
    this.isLoading = false;
  }
}

MyChildComponent :调用加载数据:

代码语言:javascript
运行
复制
  private getData() {
    this.onDataChange.emit(this.criteria);
    this.dataSource.data = this.items;
    console.log(this.dataSource);
    this.isLoading = false;
  }

调用我的子组件:

代码语言:javascript
运行
复制
<app-child-comp
                          [entity]="(user$| async)?.value?.userList"
                          (onDataChange)="getUsers($event)" 
                          class="row col-md-12"
>
</app-child-comp>

我不明白为什么我的数据源或我的项目属性在onEmit之后没有更新,而当我在我的子组件中显示json training的项目属性时,它却是最新的

EN

回答 1

Stack Overflow用户

发布于 2021-02-21 22:47:24

根据您的代码,以下是我将如何实现它,为了清楚起见,我重命名了一些内容并键入了一些对象:

服务:

代码语言:javascript
运行
复制
export interface DataUsers {
    users: User[],
    user: User
}

data$ = new BehaviorSubject({
    users: [],
    user: {}
});

constructor(​​);
  // TODO
}​​
  
public dispatch(action: Action): Observable<true | { error: string; }> {
    switch (action.type) {
        case ActionTypes.USER_LIST:
            this.callUsersApi();
            return of(true);
        default:
            return of(true);
    }
}

public getDataUsers$(): Observable<DataUsers> {
  return this.data$.asObservable();
}

private callUsersApi(): void {
  this.http
      .get('url')
      .subscribe((users: User[]) => {
        this.data$.next({...this.data$.value, users: users});
      });
}

父组件:

代码语言:javascript
运行
复制
// {...}
export class MyParentComponent implements OnInit {
  isLoading = false;
  user$: Observable<DataUsers> = null;

  constructor(private userService: UserService) {
    this.user$ = this.userService.getDataUsers$();
  }

  ngOnInit(): void {
    
  }
  
  getUsers(event) {
    this.isLoading = true;
    this.userService.dispatch({type: ActionTypes.USERR_LIST});
    // this.user$ will automatically receive the new data
    this.isLoading = false;
  }
}

父HTML (已更新管道异步):

代码语言:javascript
运行
复制
<app-child-comp
                class="row col-md-12"
                [entity]="(user$| async)?.userList"
                (onDataChange)="getUsers($event)">
</app-child-comp>

子组件:

代码语言:javascript
运行
复制
public ngOnChanges(changes: SimpleChanges) {
  if (changes.entity) {
    // this.entity has changed
    this.isLoading = false;
    if (changes.entity.currentValue) {
      // the new value is not empty
      if (!this.dataSource) {
        // init
        this.dataSource = new MatTableDataSource(changes.entity.currentValue);
      } else {
        // update
        this.dataSource.data = changes.entity.currentValue;
      }
    } else {
      // the new value is null
      if (!this.dataSource) {
        // data were displayed, reset them
        this.dataSource.data = [];
      }
    }
  }
}

private getData() {
  this.isLoading = true;
  this.onDataChange.emit(this.criteria);
  // you cannot set dataSource here, the HTTP call is not ended yet
  // when HTTP call will be ended, the ngOnChanges will be triggered because the parent will inject a new value to this.entity
  // so this.isLoading will be falsed in ngOnChanges, not here.
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/66301823

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档