Как передать идентификатор пользователя в перехватчик Angular 8 - PullRequest
2 голосов
/ 24 сентября 2019

Oke,

У меня есть приложение Angular 8, у меня есть HttpMaintenanceInterceptor, и я не использую файлы cookie для него.но:

метод getAccessToken в authService, например:

  getAccessToken(): string {
    return this._user ? this._user.access_token : null;
  }

, и у меня есть метод get.Метод get выглядит следующим образом:

getDossierEntry(type: String = '' ): Observable<DossierEntry[]> {
  const entryType = type === '' ? 'all' : 'type/' + type;
  return this.http.get<DossierEntry[]>('/api/patient/${patientUUID}/DossierEntry/' + entryType);
}

Но теперь проблема в том, что свойство:

patientUUID

всегда равно нулю.ИЛИ это результат его работы:

http://localhost:4200/api/patient/$%7BpatientUUID%7D/DossierEntry/type/physical"

Поэтому я пытаюсь отправить пациентаUUID в HttpMaintenanceInterceptor.

HttpMaintenanceInterceptor выглядит следующим образом:


export class HttpMaintenanceInterceptor implements HttpInterceptor {
  needsAuthenticatedUser = true;
  route: string;

  constructor(private auth: AuthService) {}

  intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    const accessToken = this.auth.getAccessToken();

    if (accessToken != null) {      
      console.log(accessToken);
      const duplicate = request.clone({
        setHeaders: { Authorization: `Bearer  ${accessToken}` }

      });

      const user$ = this.auth.loginStatus()
      .pipe( take( 1 ) );

       user$.pipe(
         map( user => {
          console.log('hello there nice to see you!!');
          let parsedRoute = this.route;
          if ( this.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);
           //   console.log('User Sub ' + user.profile.sub);
              console.log('User participant ' + user.profile.participant);

              parsedRoute = parsedRoute.replace('{patientUUID}', user.profile.participant);
            }
          }
          return environment.ApiOrigin + parsedRoute;
        } ),
      );


      return next.handle(duplicate);
    } else {     
      return next.handle(request);
    }
  } 
}

НоЯ не получаю PatientUUID.

Но я получаю accessToken: console.log (accessToken);выглядит так:

mIwM2U2MGNhMzgwYzczMzA2NjIcHM6Ly9k.....

Итак, мой вопрос, как передать пациенту UUID?так, чтобы в запросах API интерфейс пациентаUUID больше не был нулевым.

Спасибо

oke, я изменил на это:

getDossierEntry(type: String = '' ): Observable<DossierEntry[]> {
  const entryType = type === '' ? 'all' : 'type/' + type;
  return this.http.get<DossierEntry[]>(`/api/patient/{patientUUID}/DossierEntry/` + entryType);
}

но это не проблемаДумаю.

Поскольку проблема заключается в следующем:

console.log ('привет, рад вас видеть !!');

Не доходит до этой строки.

1 Ответ

2 голосов
/ 24 сентября 2019

Обратную кавычку следует использовать вместо простой кавычки

'/ api / Patient / $ {PatienUUID} / DossierEntry /'

скорее должно быть

`/api/patient/${patientUUID}/DossierEntry/`

То же самое имеет место при использовании parsedRoute.replace

const user$ = this.auth.loginStatus()
      .pipe( take( 1 ) );    
       user$.pipe(
         map( user => {
          console.log('hello there nice to see you!!');
          let parsedRoute = this.route;
          if ( this.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);
           //   console.log('User Sub ' + user.profile.sub);
              console.log('User participant ' + user.profile.participant);

              parsedRoute = parsedRoute.replace('{patientUUID}', user.profile.participant);
            }
          }
          return environment.ApiOrigin + parsedRoute;
        } ),
      );

Эта часть кода никогда не будет выполнена, потому что вы не подписываетесь на наблюдаемое.Вот почему значение console.log никогда не выводится на консоль

...