使用 REST 传递 JSON 对象

Pass JSON Object with REST

我有一个 rest-api-服务,其中包含以下对 REST 方法的调用,return在其响应正文中是一个非常复杂的 JSON 对象。此代码来自 rest-api-service.ts 文件。

getLocalObjectsFromREST(): Observable<LocalObjects> {
        return this.http.get<LocalObjects>(this.apiURL + '/api/GetLocalObjects')
          .pipe(
            retry(1),
            catchError(this.handleError)
          )
      }

handleError(error: { error: { message: string; }; status: any; message: any; }) {
    let errorMessage = '';
    if(error.error instanceof ErrorEvent) {
      // Get client-side error
      errorMessage = error.error.message;
    } else {
      // Get server-side error
      errorMessage = `Error Code: ${error.status}\nMessage: ${error.message}`;
    }
    console.log(errorMessage);
    return throwError(errorMessage);
  }

我正试图在我的 app.component.ts 文件中包含以下内容的组件中获取该响应:

export class AppComponent implements OnInit {

  _restApi: RestApiService | undefined;
  _localObjects: LocalObjects | undefined;

  contructor(restApi: RestApiService) {
    this._restApi = restApi;
  }

  ngOnInit() {
    this.getLocalObjectsFromService();
    console.log("Main object has a name of: " + this._localObjects?.mainObject.objName)
    console.log("Data Returned is " + this._localObjects);
  }

  getLocalObjectsFromService() {
    return this._restApi?.getLocalObjectsFromREST().subscribe((data: {}) => {
      this._localObjects = <LocalObjects> data;
    })
  }
}

我没有收到任何错误,但控制台日志显示未定义的 return 值。

有人可以帮帮我吗?

ngOnInit() {
    this.getLocalObjectsFromREST();
    console.log("Main object has a name of: " + this._localObjects?.mainObject.objName)
    console.log("Data Returned is " + this._localObjects);
  }

  getLocalObjectsFromService() {
    return this._restApi?.getLocalObjectsFromREST().subscribe((data: {}) => {
      this._localObjects = <LocalObjects> data;
    })
  }

在您的 ngOnInit() 中,您没有调用 getLocalObjectsFromService() 函数,并且由于您没有在 getLocalObjectsFromREST 之后添加 subscribe(),所以您没有看到任何数据...