私はuserServiceを作成し、私のホームコンポーネントにユーザーを取得しようとしているdotnetcore 20とangular4プロジェクトを持っています。バックエンドは正常に動作しますが、サービスは動作しません。問題はlocalstorageにあります。私が持っているエラーメッセージは:タイプ 'string'の引数null 'は' string '型のパラメータに代入不可能です。タイプ 'null'はタイプ 'string'に割り当てられません
引数 'string | null 'は' string '型のパラメータに代入不可能です。 タイプ 'string'に 'null'タイプを割り当てることはできません。
そして、私のUserServiceの
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; });
}
}
エラーがlocalStorage.getItem()
は、Aのいずれかを返すことができ、JSON.parse(localStorage.getItem('currentUser'));
はあなたが持つタイプを終了する必要がないのですか?それはnullableだと言う?私は文字列型をどこで指定しているのか分かりません。 – Carcigenicate
この場合、どちらがヌルで、どれが文字列であるかわかりません。エラーはlocalStorage上にあります。 localStorageからユーザーを取得することはできません。 – GoGo