繁体   English   中英

仅在订阅 httpClient observables 后,如何从父组件方法调用子组件方法?

[英]How to call child component method from parent component method only after subscribing httpClient observables?

如果你不介意帮助我...

最初我尝试使用 1 subscribe() 将 2 个完全不同的文件发送到 2 个完全不同的 s3 存储桶(filesArray1 到 s3 存储桶 1 和 filesArray2 到 s3 存储桶 2),但我一直面临的问题是要发送的 observable filesArray1 以某种方式被重写以将 filesArray2 发送到 s3 存储桶 1 和 s3 存储桶 2。

我知道你们中的一些人可能认为我只能进行 2 个不同的订阅,但更多的是我的用例,它们需要在 1 个订阅中,因为 file2 包含在可观察到的发送 file1 完成后的响应。它看起来像这样结束...

this.httpClient.post(apiEndpoint, filesArray1)     // retrieve S3 presign urls for each file
  .pipe(
  mergeMap( ResponseWithS3Urls => {

    const firstPostObservables = ResponseWithS3Urls.map((urls, index) => {

      return this.httpClient.post(urls, filesArray1[index]);    // Send files to S3 bucket 1
    }

    return forkJoin([forkJoin(firstPostObservables), of(ResponseWithS3Urls)]);  // Return post observables and the response from the 1st observable
  },
  mergeMap(res => {
    /* 
       Generate new JSON files (filesArray2) containing the location where each file was sent to. Do HTTP POST to get different URLS for 
       filesArray2.
       Then HTTP POST filesArray2 to those URLS.
       return 1st and 2nd set of observables to subscribe.
    */
  })
)
.subscribe(res => {
  console.log(res);
}

无论如何,我想我还是放弃了这种方法,因为我现在在想(我是 rxjs 的新手,所以这对我来说是新的)只能订阅包含一组文件的 observables ......所以我开始思考试图让一个子组件将 filesArray2 发送到 s3 存储桶 2,然后在订阅中调用该子组件..但我得到了

Cannot read property 'childComponentFunction' of undefined
  at SafeSubscriber._next (parentComponent.ts)
  at SafeSubscriber.__tryOrUnsub (Subscriber.js)
  at SafeSubscriber.next (Subscriber.js)
  at SafeSubscriber._next (Subscriber.js)
  at SafeSubscriber.next (Subscriber.js)
  at MergeMapSubscriber.notifyNext (mergeMap.js)
  at InnerSubscriber._next (InnerSubscriber.js)
  at InnerSubscriber.next (InnerSubscriber.js)
  at Object.complete (forkJoin.js)
  at Object.wrappedComplete (Subscriber.js)

我所做的只是添加

@ViewChild(ChildComponent)
private childComponent: ChildComponent

然后在

.subscribe(res => { })
 contained...
  this.childComponent.childComponentFunction(res);     // Do 2nd set of observables here instead

你们对此有任何想法吗?

您只需要附加对子模板的引用并使用该引用即可使用所有子方法。 让我们在这里举个例子。

@Component({

template : <app-child #childAccess> </app-child>

})
export class ParentComponent {
@ViewChild('childAccess', { static: false }) childComponent : ChildComponent;
childComponent.childMethod(); 
}

@Component({
selector : 'app-child'
styles :[]
template : <h1>Hello Child</h1>

})
export class ChildComponent {

  childMethod(){
  console.log('Child method works');
   }

}

暂无
暂无

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

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