0

Смотрю обучающий ролик на ютубе, как добавить token в ответное сообщение. Имеется сервис, где получаем token

  get token (): string | null {
    const fbTokenExp = localStorage.getItem('fb-token-exp');
    if (fbTokenExp) {
      const expDate = new Date(fbTokenExp);
      if ( new Date > expDate ) {
        this.logout()
        return null
      }
      return localStorage.getItem('fb-token')
    }
    return null;
  }

и сам intercept где происходит добавление token в сообщение

intercept(req: import("@angular/common/http").HttpRequest<any>,
            next: import("@angular/common/http").HttpHandler): import("rxjs").Observable<import("@angular/common/http").HttpEvent<any>> {

    if (this.auth.isAuthenticated()) {
      req = req.clone({
        setParams: {
          auth: this.auth.token
        }
      })
    }

IDEA ругается на эту строку

auth: this.auth.token

Пишет, что

TS2769: No overload matches this call.   Overload 1 of 3, '(update: { headers?: HttpHeaders | undefined; context?: HttpContext | undefined; reportProgress?: boolean | undefined; params?: HttpParams | undefined; ... 6 more ...; setParams?: { ...; } | undefined; }): HttpRequest<...>', gave the following error.     Type 'string | undefined' is not assignable to type 'string'.       Type 'undefined' is not assignable to type 'string'.   Overload 2 of 3, '(update: { headers?: HttpHeaders | undefined; context?: HttpContext | undefined; reportProgress?: boolean | undefined; params?: HttpParams | undefined; ... 6 more ...; setParams?: { ...; } | undefined; }): HttpRequest<...>', gave the following error.     Type 'string | undefined' is not assignable to type 'string'.       Type 'undefined' is not assignable to type 'string'.

Я не пойму как это исправить.

1 ответ 1

1

SetParams имеет тип:

{
 [param: string]: string;
}

Вы же скорей всего передаете значение которое может быть undefined либо сам this.auth либо его свойство this.auth.token

Проверяйте существует ли свойство

if (this.auth && this.auth.token) {
  req = req.clone({
    setParams: {
      auth: this.auth.token
    }
  })
}

Либо используйте оператор ! если уверены что свойство есть

if (this.auth.isAuthenticated()) {
    req = req.clone({
      setParams: {
        auth: this.auth!.token!
      }
    })
 }

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.