繁体   English   中英

Angular 当我使用 Observables 时 ViewChild 不工作

[英]Angular ViewChild Not Working When I Use Observables

我在我的 web 应用程序中使用Angular 10NGXS 3.7.0作为我的 state 管理框架。

我的应用程序中有两个组件; 假设ParentComponentChildComponent ChildComponent有一个名为resources的字段,它是一个ResourceInterface数组,默认情况下等于一个空数组(即[] )。 ChildComponent内部还有一个Run按钮,它发出一个 EventEmitter 来通知ParentComponent最终用户点击了Run按钮; 因此,嘿,父亲,从服务器获取资源,然后更新我的resources字段。

问题是,在ParentComponent中,当我不使用 Observables 时它可以工作,但是当我订阅 observable 时它就不起作用。 事实上,我必须使用 observable 并且没有 observable 就无法做我的事情。 在下一节中,我提供了代码。

Child Component

@Component({
  selector: '...',
  templateUrl: '...',
  styleUrls: ['...'],
  changeDetection: ChangeDetectionStrategy.OnPush
})
export class ChildComponent implements OnInit {
  resources: ResourceInterface[] = [];
      
  @Output() runRequest: EventEmitter<void>;

  constructor() {
    this.runRequest = new EventEmitter<void>();
  }
  
  onRunRequest(): void {
    this.runRequest.emit();
  }
}

Parent Component

@Component({
  selector: '...',
  templateUrl: '...',
  styleUrls: ['...'],
  changeDetection: ChangeDetectionStrategy.OnPush
})
export class ParentComponent implements OnInit {
  rId: string;
  request$: Observable<DURequest | undefined>;
  @ViewChild(ChildComponent) child!: ChildComponent;

  constructor(
    private _service: DURService,
    private _rService: RService,
    private route: ActivatedRoute,
  ) {
    this.rId = this.route.snapshot.paramMap.get('id')!;
    this.request$ = this.rId ? this._service.watchDUR(this.rId) : of(undefined);
  }

  onRunRequest(): void {
    // This block works
    this.request$.subscribe(req => {
      this.child.resources = [
        {
          Id: '123',
          fullUrl: 'some full url'
        }
      ];
    });

    // This block does NOT work
    // this.request$.subscribe(req => {
    //   this._service.runRequest(req!).subscribe(res => {
    //     this.child.resources = [
    //       {
    //         Id: '123',
    //         fullUrl: 'some full url'
    //       }
    //     ];
    //   });
    // });

    // This block does NOT work
    // this.request$.subscribe(req => {
    //   this._service.runRequest(req!).subscribe(res => {
    //     this._service.fetchResources().subscribe(resources => {
    //       this.child.resources = [
    //         {
    //           Id: '123',
    //           fullUrl: 'some full url'
    //         }
    //       ];
    //     });
    //   });
    // });

    // The actual code should be this one, but this one does NOT work, too
    // this.request$.subscribe(req => {
    //   this._service.runRequest(req!).subscribe(res => {
    //     this._service.fetchResources().subscribe(resources => {
    //       this.child.resources = resources;
    //     });
    //   });
    // });
  }
}

@ViewChild(组件,{ static:真}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM