【发布时间】:2018-04-05 12:21:58
【问题描述】:
我有一个 dotnetcore 20 和 angular4 项目,我正在尝试创建一个 userService 并让用户访问我的主组件。后端工作得很好,但服务却不行。问题出在 localStorage 上。我收到的错误消息是:
'string | 类型的参数null' 不能分配给“字符串”类型的参数。 类型 'null' 不能分配给类型 'string'。
还有我的用户服务
import { User } from './../models/users';
import { AppConfig } from './../../app.config';
import { Injectable } from '@angular/core';
import { Http, Headers, RequestOptions, Response } from '@angular/http';
@Injectable()
export class UserService {
constructor(private http: Http, private config: AppConfig) { }
getAll() {
return this.http.get(this.config.apiUrl + '/users', this.jwt()).map((response: Response) => response.json());
}
getById(_id: string) {
return this.http.get(this.config.apiUrl + '/users/' + _id, this.jwt()).map((response: Response) => response.json());
}
create(user: User) {
return this.http.post(this.config.apiUrl + '/users/register', user, this.jwt());
}
update(user: User) {
return this.http.put(this.config.apiUrl + '/users/' + user.id, user, this.jwt());
}
delete(_id: string) {
return this.http.delete(this.config.apiUrl + '/users/' + _id, this.jwt());
}
// private helper methods
private jwt() {
// create authorization header with jwt token
let currentUser = JSON.parse(localStorage.getItem('currentUser'));
if (currentUser && currentUser.token) {
let headers = new Headers({ 'Authorization': 'Bearer ' + currentUser.token });
return new RequestOptions({ headers: headers });
}
}
而我的 home.component.ts 是
import { UserService } from './../services/user.service';
import { User } from './../models/users';
import { Component, OnInit } from '@angular/core';
@Component({
moduleId: module.id,
templateUrl: 'home.component.html'
})
export class HomeComponent implements OnInit {
currentUser: User;
users: User[] = [];
constructor(private userService: UserService) {
this.currentUser = JSON.parse(localStorage.getItem('currentUser'));
}
ngOnInit() {
this.loadAllUsers();
}
deleteUser(_id: string) {
this.userService.delete(_id).subscribe(() => { this.loadAllUsers() });
}
private loadAllUsers() {
this.userService.getAll().subscribe(users => { this.users = users; });
}
错误在JSON.parse(localStorage.getItem('currentUser'));
【问题讨论】:
-
您不必以 结束类型吗?说它可以为空?我不确定你在哪里指定字符串类型。
-
在这种情况下,我什至不知道哪个是null,哪个是字符串。错误出现在 localStorage 上。它只是没有从 localStorage 获取用户。
标签: angular typescript