首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >api调用在角8中,结果未定义。

api调用在角8中,结果未定义。
EN

Stack Overflow用户
提问于 2019-09-23 07:53:36
回答 4查看 2.1K关注 0票数 1

我有一个角8应用程序,想要调用一个Get调用。

但我知道这个错误:

代码语言:javascript
复制
stack: "ReferenceError: result is not defined↵    at eval (eval at push../src/app/dossier/dossier-physical/dossier-physical.component.ts.DossierPhysicalComponent.ngOnInit 

这是ts文件:

代码语言:javascript
复制
export class DossierPhysicalComponent implements OnInit {
  entries: Array<DossierEntry> = [];
  single: DossierEntry;
  showSingle: boolean;
  dossiersLoaded = false;

  constructor(
    private healthAPIService: HealthAPIService,
    private documentCorrespondencService: DocumentCorrespondenceService
  ) {}

  ngOnInit() {
    this.healthAPIService.getDossierEntry('physical').subscribe(result => {
      console.log(result.values);
      this.entries = result;
      this.dossiersLoaded = true;
    });
  }
}

这就是服务:

代码语言:javascript
复制
 getDossierEntry( type: String = '' ): Observable<DossierEntry[]> {
    const entryType = type === '' ? 'all' : 'type/' + type;
    return this.http.get<DossierEntry[]>('/api/patient/{patientUUID}/DossierEntry/' + entryType );
  }

这是总的错误

代码语言:javascript
复制
HttpErrorResponse {headers: HttpHeaders, status: 404, statusText: "Not Found", url: "http://localhost:4200/api/patient/%7BpatientUUID%7D/DossierEntry/type/physical", ok: false, …}
error: "<!DOCTYPE html>↵<html lang="en">↵<head>↵<meta charset="utf-8">↵<title>Error</title>↵</head>↵<body>↵<pre>Cannot GET /api/patient/%7BpatientUUID%7D/DossierEntry/type/physical</pre>↵</body>↵</html>↵"
headers: HttpHeaders {normalizedNames: Map(0), lazyUpdate: null, lazyInit: ƒ}
message: "Http failure response for http://localhost:4200/api/patient/%7BpatientUUID%7D/DossierEntry/type/physical: 404 Not Found"
name: "HttpErrorResponse"
ok: false
status: 404
statusText: "Not Found"
url: "http://localhost:4200/api/patient/%7BpatientUUID%7D/DossierEntry/type/physical"
__proto__: HttpResponseBase

我在这里做错了什么?

谢谢

问题是,我试图重构Get方法。因为我有一个服务: health.api.service。

还有定制的api调用。如下所示:

代码语言:javascript
复制
 get( route: string, responseType: RespType = 'json', fullResponse: boolean = false, params = null): Observable<any> {
    return this.invoke( 'GET', route, null, responseType, fullResponse, true, params);
  }

invoke方法如下所示:

代码语言:javascript
复制
 invoke(
    method: 'GET' | 'POST' | 'PUT' | 'DELETE',
    route: string,
    body?: any,
    responseType: RespType = 'json', // PDF gets translated to array buffer and the application/pdf accept header
    fullResponse: boolean  = false,
    needsAuthenticatedUser = true,
    params: HttpParams = null
  ): Observable<any> {
    const user$ = this.authService.loginStatus()
                      .pipe( take( 1 ) );

    return user$.pipe(
      map( user => {
        let parsedRoute = route;
        if ( needsAuthenticatedUser ) {
          if ( !user ) {
            throw Error( 'Tried to call api that requires login without a user profile present' );
          } else {
            parsedRoute = parsedRoute.replace('{userId}', user.profile.sub);
            parsedRoute = parsedRoute.replace('{patientUUID}', user.profile.participant);
          }
        }
        return environment.ApiOrigin + parsedRoute;
      } ),
      switchMap( url => {
        const accessToken = this.authService.getAccessToken();

        const headers = {
          'Content-Type': 'application/json',
          'Accept'      : HealthAPIService._responseTypes[ responseType ].mime
        };

        if ( !!accessToken ) {
          headers[ 'Authorization' ] = `Bearer  ${accessToken}`;
        }

        const options = {
          body        : body,
          responseType: HealthAPIService._responseTypes[ responseType ].decode as
            | 'json'
            | 'text'
            | 'arraybuffer',
          headers     : new HttpHeaders( headers )
        };
        if ( fullResponse ) {
          options[ 'observe' ] = 'response';
        }
        if (params !== null) {
          options['params'] = params;
        }

        return this.http.request( method, url, options )
                   .pipe( catchError(err => this.handleError(err)) );
      } )
    );
  }

但我想摆脱那种定制的get方法。只想用角的HttpClient模块来调用它。

这是错误处理:

代码语言:javascript
复制
private handleError( error: any ): Observable<any> {
    if ( error.status && error.status === 401 ) {
      console.error( 'Authorization failed, trying to login.' );
      this.authService.requestLogin();
    }
    console.dir( error );
    if ('error' in error) {
      // This is necessary to allow measurement-form-component
      // handleFormErrors to give correct feedback.
      return observableThrowError(error);
    }
    return observableThrowError( error.message || error );
  }

当我尝试的时候。我仍然会得到这个错误:

代码语言:javascript
复制
HttpErrorResponse {headers: HttpHeaders, status: 404, statusText: "Not Found", url: "http://localhost:4200/api/patient/%7BpatientUUID%7D/DossierEntry/type/physical", ok: false, …}
error: "<!DOCTYPE html>↵<html lang="en">↵<head>↵<meta charset="utf-8">↵<title>Error</title>↵</head>↵<body>↵<pre>Cannot GET /api/patient/%7BpatientUUID%7D/DossierEntry/type/physical</pre>↵</body>↵</html>↵"
headers: HttpHeaders {normalizedNames: Map(0), lazyUpdate: null, lazyInit: ƒ}
message: "Http failure response for http://localhost:4200/api/patient/%7BpatientUUID%7D/DossierEntry/type/physical: 404 Not Found"
name: "HttpErrorResponse"
ok: false
status: 404
statusText: "Not Found"
url: "http://localhost:4200/api/patient/%7BpatientUUID%7D/DossierEntry/type/physical"
__proto__: HttpResponseBase
constructor: ƒ HttpErrorResponse(init)
__proto__: Object

所以我现在有这样的想法:

代码语言:javascript
复制
 ngOnInit() {
    this.healthAPIService.getDossierEntry('physical').subscribe((result: any)=> {
       console.log(result.values);
       this.entries = result;
       this.dossiersLoaded = true;
   });
 }

这是:

代码语言:javascript
复制
  getDossierEntry( type: String = '' ): Observable<DossierEntry[]> {
    const entryType = type === '' ? 'all' : 'type/' + type;
    return this.http.get<DossierEntry[]>('/api/patient/{patientUUID}/DossierEntry/' + entryType );
  }

然后我会得到这个错误:

代码语言:javascript
复制
core.js:7376 ERROR 
HttpErrorResponse {headers: HttpHeaders, status: 404, statusText: "Not Found", url: "http://localhost:4200/api/patient/%7BpatientUUID%7D/DossierEntry/type/physical", ok: false, …}
error: "<!DOCTYPE html>↵<html lang="en">↵<head>↵<meta charset="utf-8">↵<title>Error</title>↵</head>↵<body>↵<pre>Cannot GET /api/patient/%7BpatientUUID%7D/DossierEntry/type/physical</pre>↵</body>↵</html>↵"
headers: HttpHeaders {normalizedNames: Map(0), lazyUpdate: null, lazyInit: ƒ}
message: "Http failure response for http://localhost:4200/api/patient/%7BpatientUUID%7D/DossierEntry/type/physical: 404 Not Found"
name: "HttpErrorResponse"
ok: false
status: 404
statusText: "Not Found"
url: "http://localhost:4200/api/patient/%7BpatientUUID%7D/DossierEntry/type/physical"
__proto__: HttpResponseBase
代码语言:javascript
复制
stack: "ReferenceError: result is not defined↵    at eval (eval at push../src/app/dossier/dossier-physical/dossier-physical.component.ts.DossierPhysicalComponent.ngOnInit (http://localhost:4200/dossier-dossier-module-ngfactory.js:18184:14), <anonymous>:1:1)↵    at DossierPhysicalComponent.push../src/app/dossier/dossier-physical/dossier-physical.component.ts.DossierPhysicalComponent.ngOnInit (http://localhost:4200/dossier-dossier-module-ngfactory.js:18184:14)↵    at checkAndUpdateDirectiveInline (http://localhost:4200/vendor.js:37850:19)↵    at checkAndUpdateNodeInline (http://localhost:4200/vendor.js:46063:20)↵    at checkAndUpdateNode (http://localhost:4200/vendor.js:46025:16)↵    at debugCheckAndUpdateNode (http://localhost:4200/vendor.js:46659:38)↵    at debugCheckDirectivesFn (http://localhost:4200/vendor.js:46619:13)↵    at Object.updateDirectives (http://localhost:4200/dossier-dossier-module-ngfactory.js:18152:711)↵    at Object.debugUpdateDirectives [as updateDirectives] (http://localhost:4200/vendor.js:46611:21)↵    at checkAndUpdateView (http://localhost:4200/vendor.js:46007:14)"

这是HttpMaintenanceInterceptor:

代码语言:javascript
复制
@Injectable({
    providedIn: 'root'
  })
export class HttpMaintenanceInterceptor implements HttpInterceptor {

    constructor(private auth: AuthService ) {
    }

    intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {

      request = request.clone({
        setHeaders: {
          Authorization: `Bearer ${this.auth.getAccessToken()}`
        }
      });
      return next.handle(request);
    }
}

我现在有这样的感觉:

代码语言:javascript
复制
getDossierEntry( patientUUID: string, type: String = '' ): Observable<DossierEntry[]> {
  const entryType = type === '' ? 'all' : 'type/' + type;

  console.log(this.http.get<DossierEntry[]>('/api/patient/' + patientUUID + '/DossierEntry/' + entryType));

  return this.http.get<DossierEntry[]>('/api/patient/${patientUUID}/DossierEntry/' + entryType);
}

这是:

代码语言:javascript
复制
 ngOnInit() {
    this.documentCorrespondencService.getDossierEntry('physical').subscribe((result: any)=> {
       console.log(result.values);
       this.entries = result;
       this.dossiersLoaded = true;
   });
 }

我得到了这个输出:

代码语言:javascript
复制
Observable {_isScalar: false, source: Observable, operator: MapOperator}
operator: MapOperator
project: ƒ (res)
thisArg: undefined
__proto__: Object
source: Observable {_isScalar: false, source: Observable, operator: FilterOperator}
_isScalar: false
__proto__: Object
代码语言:javascript
复制
HttpErrorResponse {headers: HttpHeaders, status: 404, statusText: "Not Found", url: "http://localhost:4200/api/patient/$%7BpatientUUID%7D/DossierEntry/all", ok: false, …}
error: "<!DOCTYPE html>↵<html lang="en">↵<head>↵<meta charset="utf-8">↵<title>Error</title>↵</head>↵<body>↵<pre>Cannot GET /api/patient/$%7BpatientUUID%7D/DossierEntry/all</pre>↵</body>↵</html>↵"
headers: HttpHeaders {normalizedNames: Map(0), lazyUpdate: null, lazyInit: ƒ}
message: "Http failure response for http://localhost:4200/api/patient/$%7BpatientUUID%7D/DossierEntry/all: 404 Not Found"
name: "HttpErrorResponse"
ok: false
status: 404
statusText: "Not Found"
url: "http://localhost:4200/api/patient/$%7BpatientUUID%7D/DossierEntry/all"
__proto__: HttpResponseBase

即使我这么做:

代码语言:javascript
复制
getDossierEntry( patientUUID: string, type: String = '' ): Observable<DossierEntry[]> {
  patientUUID = '0d584905-fc20-4723-870a-0f0214419507';
  const entryType = type === '' ? 'all' : 'type/' + type;

  console.log(this.http.get<DossierEntry[]>('/api/patient/' + patientUUID + '/DossierEntry/' + entryType ));

  console.log(patientUUID);
  return this.http.get<DossierEntry[]>('/api/patient/' + patientUUID + '/DossierEntry/' + entryType );
}

深层次工作

EN

回答 4

Stack Overflow用户

回答已采纳

发布于 2019-09-23 16:05:19

为了达到预期效果,请使用下面的选项使用patientUUID更新API url

选项1:

代码语言:javascript
复制
 getDossierEntry( patientUUID: string, type: String = '' ): Observable<DossierEntry[]> {
    const entryType = type === '' ? 'all' : 'type/' + type;
    return this.http.get<DossierEntry[]>('/api/patient/' + patientUUID + '/DossierEntry/' + entryType );
  }

选项2:在URL中使用patientUUID的其他方式

代码语言:javascript
复制
getDossierEntry( patientUUID: string, type: String = '' ): Observable<DossierEntry[]> {
        const entryType = type === '' ? 'all' : 'type/' + type;
        return this.http.get<DossierEntry[]>('/api/patient/${patientUUID}/DossierEntry/' + entryType);
  }

问题patientUUID值没有在指定位置被附加到URL,也没有被找到,因为结果证明是无效的。

若要修复此问题,请使用参数- patientUUID类型更新API url,并在返回之前调试add控制台以检查url如下所示

代码语言:javascript
复制
console.log(this.http.get<DossierEntry[]>('/api/patient/' + patientUUID + '/DossierEntry/' + entryType)
票数 1
EN

Stack Overflow用户

发布于 2019-09-23 07:56:20

正如我所看到的,您得到的响应是404,这意味着没有找到URL。

在你的代码中,

您不能替换可以签入patientUUID的值

代码语言:javascript
复制
return this.http.get<DossierEntry[]>('/api/patient/{patientUUID}/DossierEntry/' + entryType
票数 0
EN

Stack Overflow用户

发布于 2019-09-23 07:56:54

在开发人员模式下,您应该添加proxy.conf.json以转发到服务器:例如:

代码语言:javascript
复制
{
  "/api": {
    "target": "http://localhost:1337",
    "secure": false
  }
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/58057875

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档