Angular 4 - TypeError:无法读取属性的'长度'null
这是一个基本的Angular 4
应用程序,其中Django Rest framework
作为后端。我使用JWT
令牌进行身份验证。当我单击登录按钮时,显示此错误。我找不到为什么会发生这种情况。我是新来Typescript
和Angular 4
,希望有人能解决这个疑难问题都试图改变signInComponent.html
,但问题并没有解决Angular 4 - TypeError:无法读取属性的'长度'null
** ** 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']);
}
}
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']);
}
}
试试看?在userService –
我使用HttpClient,所以我认为这将不会工作,而不是从'@ angular/http导入{Http,Headers}我使用{HttpClientModule}从 '@ angular/common/http –
你的代码在这里运行。没有'长度'问题 –
你在哪里读取length属性 –
@RahulSingh作为'有错误:'在控制台中记录我认为它是在订阅功能的错误回调。 Basim可以使用详细视图中的登录调用发布网络选项卡的屏幕截图吗? – Dhyey
@Dhyey我添加了屏幕截图 –