Angular 4 - TypeError:无法读取 null 的属性“长度”

Posted

技术标签:

【中文标题】Angular 4 - TypeError:无法读取 null 的属性“长度”【英文标题】:Angular 4 - TypeError: Cannot read property 'length' of null 【发布时间】:2018-03-27 15:10:19 【问题描述】:

这是一个基本的Angular 4 应用程序,以Django Rest framework 作为后端。我正在使用JWT 令牌进行身份验证。当我单击登录按钮时,会显示此错误。我找不到为什么会这样。我是TypescriptAngular 4 的新手,希望有人能解决这个问题。我尝试更改signInComponent.html 但问题没有解决

** SignInComponent.ts**

import  NgForm  from '@angular/forms/src/directives';
import  Router  from '@angular/router';
import  Component, OnInit  from '@angular/core';
import  UserService  from '../../services/user.service';

@Component(
selector: 'app-sign-in',
templateUrl: './sign-in.component.html',
styleUrls: ['./sign-in.component.css']
)
export class SignInComponent 
token=null ;  
formError: string;
submitting = false;

constructor(private router:Router, private authService:UserService)  

onSubmit(signInForm: NgForm ) 

if (signInForm.valid) 

  console.log('submitting...', signInForm);
  this.submitting = true;
  this.formError = null;

  this.authService.login(signInForm.value.username, 
signInForm.value.password)
    .subscribe((data) => 
        this.token=data['data'];
        console.log( this.token['token'])
        this.authService.saveJWT(this.token['token']);
        this.authService.isAuthenticated =true;
        this.router.navigate(['/auth']);
      ,
      (err)=> 
        this.submitting = false;
        console.log('got error: ', err);
        this.formError = err;
        this.router.navigate(['/login']);
      
    );


 this.authService.ping().subscribe((data) => 
  console.log('got token yeeh: ');
  console.log(this.authService.getJwt());
  ,
  );

 

** SignInComponent.html**

<div class="sign-in-form">
<img src="./assets/logo.jpg"  />
<h4>Sign In</h4>
<form #signInForm="ngForm" (ngSubmit)="onSubmit(signInForm)" novalidate>
<div class="form-group">
<input class="form-control" name="username" required placeholder="User Name" 
ngModel #username="ngModel" />
<div [hidden]="username.valid || username.pristine" class="alert alert-
danger">
User Name is required.
</div>
</div>
<div class="form-group">
<input class="form-control" name="password" required type="password"  
placeholder="Password" ngModel #password="ngModel"/>
  <div [hidden]="password.valid || password.pristine" class="alert alert-
danger">
    Password is required.
  </div>
</div>
<div class="checkbox">
  <label>
  <input type="checkbox" name="rememberMe" ngModel /> Remember Me
  </label>
</div>
<div *ngIf="formError" class="alert alert-danger">
   formError 
</div>
<div *ngIf="!submitting">
  <button type="submit" class="btn btn-primary">Sign In</button>
</div>
<div *ngIf="submitting">
  <p class="message">Signing In...</p>
</div>

</form>
</div>

** AuthService.ts**

import  any  from 'codelyzer/util/function';
import  Injectable, OnInit  from '@angular/core';
import  Router  from '@angular/router';
import  HttpClient   from '@angular/common/http';
import  Observable  from 'rxjs/Rx';
import  HttpHeaders  from '@angular/common/http';

@Injectable()
export class UserService  


 isAuthenticated = false;

 constructor(private router: Router ,private http:HttpClient  )  

 

 saveJWT(strToken: string): any 
 localStorage.setItem('JWT',strToken);
 

 login(username: string, password: string):Observable<any> 

 let headers =new HttpHeaders();
 var body = "username="+username+"&password="+password;
 headers = headers.set("Content-Type", "application/x-www-form-urlencoded");
 return  this.http.post('http://nucore.ddns.net:800/v1/user/login', body, 
   headers:headers);
 
 getJwt():string


 return localStorage.getItem('JWT');


ping():Observable<any> 
return this.http.get('https://jsonplaceholder.typicode.com/users')



logOut() 
// remove user from local storage to log user out
localStorage.removeItem('JWT');
this.isAuthenticated = false;
this.router.navigate(['/login']);





网络截图

【问题讨论】:

你在哪里读到那个长度属性 @RahulSingh as 'got error: ' 记录在控制台中,我认为它正在订阅函数的错误回调中。 Basim 可以在详细视图中发布带有登录调用的网络选项卡的屏幕截图吗? @Dhyey 我添加了截图 @BasimE-Darussalam 这不是登录调用。这只是一个 webpack 调用,它在内部用于实时重新加载和其他内容。你可以点击调用authService.login方法的登录按钮然后发布截图 @Dhyey 是你想要的吗? 【参考方案1】:

发布这个作为答案是因为我在从 Angular 2 迁移到 Angular 6 时花了一整天的时间试图解决这个问题,而且我确信有人也有同样的错误。

问题在于 http 拦截器将身份验证令牌添加到登录请求中,此时身份验证令牌为空。所以请确保 authinterceptor 不会尝试将令牌添加到登录请求中

【讨论】:

我已经尝试了 6 个多小时来解决这个问题。谢谢。【参考方案2】:
import Injectable from '@angular/core';
import Router from '@angular/router';
import Observable from 'rxjs';
import Http, Headers from '@angular/http';

@Injectable()
export class UserService 


  isAuthenticated = false;

  constructor(private router: Router, private http: Http) 

  

  saveJWT(strToken: string): any 
    localStorage.setItem('JWT', strToken);
  

  login(username: string, password: string): Observable<any> 

    const head = new Headers();
    const body = 'username=' + username + '&password=' + password;
    head.set('Content-Type', 'application/x-www-form-urlencoded');
    return this.http.post('http://nucore.ddns.net:800/v1/user/login', body, 
      headers: head
    );
  

  getJwt(): string 

    return localStorage.getItem('JWT');

  

  ping(): Observable<any> 
    return this.http.get('https://jsonplaceholder.typicode.com/users')

  

  logOut() 
// remove user from local storage to log user out
    localStorage.removeItem('JWT');
    this.isAuthenticated = false;
    this.router.navigate(['/login']);
  



【讨论】:

试一试?在用户服务处 我正在使用 HttpClient,所以我认为这不会起作用,而不是 import Http, Headers from '@angular/http 我使用 HttpClientModule from '@angular/common/http 您的代码正在此处运行。不存在“长度”问题 是的,这个项目运行良好,但突然我得到了这些错误,而没有更改代码中的任何内容 @BasimE-Darussalam 很抱歉恢复旧线程,但我面临着同样的问题。你找到解决办法了吗?

以上是关于Angular 4 - TypeError:无法读取 null 的属性“长度”的主要内容,如果未能解决你的问题,请参考以下文章

角度单元测试:TypeError:无法读取未定义的属性“根”

Angular - 调度动作时出现“TypeError:无法冻结”

Angular给出TypeError:“无法读取未定义的属性'id'”

Angular 2:TypeError:无法读取未定义的属性“isRouteActive”

Angular 6:TypeError:无法读取未定义的属性“值”

Angular,TypeError:无法读取未定义的属性“排序”