簡體   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