尝试创建一个真实世界的应用程序来包装我的api,我只是不确定如何调试此错误。
在lists.service中构造“private authService”似乎是错误的根本原因。登录组件工作正常。
EXCEPTION:未捕获(承诺):错误:DI错误错误:DI错误 at NoProviderError.ZoneAwareError(http://localhost:4200/polyfills.bundle.js:3270:33) 在NoProviderError.BaseError [作为构造函数](http://localhost:4200/vendor.bundle.js:29085:16) 在NoProviderError.AbstractProviderError [作为构造函数](http://localhost:4200/vendor.bundle.js:57951:16) 在新的NoProviderError(http://localhost:4200/vendor.bundle.js:58013:16) 在ReflectiveInjector _._ throwOrNull(http://localhost:4200/vendor.bundle.js:78274:19)........
列出要获取列表的服务。
import { Injectable } from '@angular/core';
import { Http, Headers, RequestOptions, Response } from '@angular/http';
import { Observable } from 'rxjs';
import 'rxjs/add/operator/map';
import { AuthService } from '../auth/auth.service';
@Injectable()
export class ListsService {
constructor(private http: Http, private authService: AuthService) { }
getLists(): Observable<boolean> {
// add jwt token to headers
let headers = new Headers({ 'Authorization': 'Bearer ' + this.authService.token });
let options = new RequestOptions({ headers: headers });
return this.http.post('http://localhost:8080/lists', options)
.map((response: Response) => response.json());
}
}
验证服务以获取令牌
import { Injectable } from '@angular/core';
import { Http, Headers, Response } from '@angular/http';
import { Observable } from 'rxjs';
import 'rxjs/add/operator/map'
@Injectable()
export class AuthService {
public token: string;
constructor(private http: Http) {
let currentUser = JSON.parse(localStorage.getItem('currentUser'));
this.token = currentUser && currentUser.token;
}
login(email: string, password: string): Observable<boolean> {
return this.http.post('http://localhost:8080/login', { email: email, password: password })
.map((response: Response) => {
let token = response.json() && response.json().token;
if (token) {
// set token
this.token = token;
localStorage.setItem('currentUser', JSON.stringify({ email: email, token: token }));
return token;
} else {
return false;
}
}
);
}
logout(): void {
this.token = null;
localStorage.removeItem('currentUser');
}
}
答案 0 :(得分:1)
看起来您是否希望服务(例如auth)可用于您需要将其作为提供程序包含在app.module中的所有其他服务