在Angular中返回Observable时出错

时间:2019-12-05 15:28:52

标签: angular http observable

我可以通过以下方法向REST API发出发布请求:

postTextToSentimentAnalysis(userTextInput: string): Observable<any> {
  let authenticatedUser = this.auth.getAuthenticatedUser();
  if (authenticatedUser == null) {
    return;
  }
  authenticatedUser.getSession( (err, session) => {
    if (err) {
      console.log(err);
      return;
    }
    const token = session.getIdToken().getJwtToken();
    const headers = new Headers();
    headers.append('Authorization', token);
    this.auth.getAuthenticatedUser().getSession((err, session) => {
      if (err) {
        console.log(err);
        return;
      }
      const token = session.getIdToken().getJwtToken();
      const headers = new HttpHeaders();
      headers.append('Authorization', token);
      return this.httpClient.post('http://example.com:12445/sentiment-analysis/sentiment-analysis-function', userTextInput, { headers: {'Authorization': token} })});
  });
}

在调用函数的方法中,我要订阅Observable:

analyseText(){
console.log("Analyse Input: " + this.sentimentTextInput);
this.sentimentManagementService.postTextToSentimentAnalysis(this.sentimentTextInput).subscribe(res => {
  console.log(res);
  //this.sentimentTextResult = res;
}, error => {
  console.log(error);
});
}

调用此函数时,出现以下错误:

SentimentAnalysisComponent.html:4 ERROR TypeError: Cannot read property 'subscribe' of undefined
at SentimentAnalysisComponent.analyseText (sentiment-analysis.component.ts:21)
at Object.eval [as handleEvent] (SentimentAnalysisComponent.html:6)
at handleEvent (core.js:43993)
at callWithDebugContext (core.js:45632)
at Object.debugHandleEvent [as handleEvent] (core.js:45247)
at dispatchEvent (core.js:29804)
at core.js:42925
at HTMLButtonElement.<anonymous> (platform-browser.js:2668)
at ZoneDelegate.invokeTask (zone-evergreen.js:391)
at Object.onInvokeTask (core.js:39680)

第21行是我调用subscribe()函数的地方。

getAuthenticatedUser() {
// gets the current user from the local storage
return userPool.getCurrentUser();
}

1 个答案:

答案 0 :(得分:0)

您没有在postTextToSentimentAnalysis中返回Observable。

创建一个调用this.auth.getAuthenticatedUser().getSession并在回调中发出所需资源的Observable。用户switchMap将该令牌映射到您的http请求。

getToken(): Observable<string> {
  return new Observable<string>(observer => {
    if (this.auth.getAuthenticatedUser() != null) {
      this.auth.getAuthenticatedUser().getSession((err, session) => {
        if (err) {
          observer.error(err);
          return;
        }
        observer.next(session.getIdToken().getJwtToken()); // emit token
        observer.complete();
      });
    } else {
      observer.complete(); // or observer.error('mymessage') if this is an error case
    }
  });
}

postTextToSentimentAnalysis(userTextInput: string): Observable<any> {
  return this.getToken().pipe(
    switchMap(token => this.httpClient.post(
      'http://example.com:12445/sentiment-analysis/sentiment-analysis-function', 
      userTextInput, 
      { headers: new HttpHeaders({ 'Authorization': token }) }
    ))
  );
}