开发者问题收集

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

2017-10-16
3865

这是一个基本的 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" width="320" />
<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']);
}



}

网络截图 在此处输入图片说明

在此处输入图片说明

在此处输入图片说明

2个回答

发布此内容作为答案,因为我刚刚花了一整天时间试图从 Angular 2 迁移到 Angular 6 时弄清楚了这一点,而且我确信有人也犯了同样的错误。

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

Joakim
2018-06-05
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']);
  }


}
Coco
2017-10-16