【问题标题】:what is the correct way to check variable is present in http response?检查http响应中是否存在变量的正确方法是什么?
【发布时间】:2019-12-11 05:14:17
【问题描述】:

我已经创建了这个服务来处理身份验证,它工作正常......

import { HttpClient, HttpHeaders } from '@angular/common/http';
import { tap } from 'rxjs/operators';
import { Storage } from '@ionic/storage';
import { EnvService } from './env.service';
import { Injectable } from '@angular/core';

@Injectable({
  providedIn: 'root'
})

export class AuthService {

  isLoggedIn = false;
  token:any;

  constructor(
    private storage:Storage,
    private http: HttpClient,
    private env: EnvService,
  ) { }

  login(email: String, password: String) {

    let formData = {
      usuario    : email,
      senha      : password,
      retsession : true
    }

    return this.http.post(this.env.API_URL+'/login', formData).pipe(
      tap(response => {
        var token = ('jwt' in response) ? response.jwt : null ;
        this.storage.set('token', token)
        .then(
          () => { console.log('Token Stored: ' + token); },
          error => console.error('Error storing item', error)
        );
        this.token = token;
        this.isLoggedIn = true;
        return token;
      }),
    );
  }

}

即使它工作正常,我也会遇到编译错误

[ng] ERROR in src/app/services/auth.service.ts(36,52): error TS2339: Property 'jwt' does not exist on type 'never'.

当我检查我的令牌是否存在于 http 响应数据中时,出现此错误...

检查这个避免这个错误的正确方法是什么?

【问题讨论】:

  • 服务器正在响应 json 数据
  • 响应如何?请举个例子。
  • {"jwt":"<my_token_here>", "user_id":"my_user_id_here"}
  • 我会这样验证: let token = response['jwt] !== undefined && response['jwt'] !== ' ' ?响应['jwt'] : null ;
  • 只是一个建议,但您应该将输入信息传递到您的帖子请求中。 this.http.post(URL, data).subscribe((response

标签: angular typescript ionic-framework


【解决方案1】:

要检查令牌是否存在,您可以这样做:

let token = response['jwt'] ? response['jwt'] : null ;

亲切的问候

【讨论】:

    【解决方案2】:

    sagat 的回答是正确的。下面是一个如何将接口传递给 http 调用的示例:

    // form-data.interface.ts
    export interface FormData {
      usuario: string;
      senha: string;
      retsession: boolean;
    }
    
    // login-response.interface.ts
    export interface LoginResponse {
      jwt: string;
      // other properties
    }
    
    // login.service.ts
    login(formData: FormData): Obvservable<LoginResponse> {
      return this.http.post<LoginResponse>(`${this.env.API_URL}/login`, formData);
    }
    
    // call this from your component (login.component.ts) or your state management (login.state.ts)
    // call it like so
    this.login(formData).subscribe((response) => {
      // perform your logic with the response
    }
    

    您的 http 帖子将返回一个您可以订阅的 observable。这里不需要管道和水龙头,但基本上做同样的事情。

    注意: 如果您没有收到您期望的属性值,而不是接口,您可以使用如下类:

    // login.response.model.ts
    export class LoginResponse {
      jwt: string
      // other properties
    
      constructor(data: LoginResponse) {
        this.jwt = (data && data.jwt) ? data.jwt : '';
      }
    }
    

    此方法将确保模型上存在所有属性并设置并具有初始值。如果缺少数据,您不会遇到任何错误。

    【讨论】:

    • 您能否编辑描述每个代码块的文件名的答案? afaik 登录方法应该投入使用,并且应该从带有订阅的控制器调用...对吗?
    猜你喜欢
    • 1970-01-01
    • 2011-07-19
    • 2019-09-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-18
    • 1970-01-01
    • 2013-01-13
    相关资源
    最近更新 更多