我无法理解如何在Angular 2应用程序的其他部分使用在根级别注入的提供程序。
我有一个帮助JWT身份验证的工厂提供程序angular2-jwt。我把它注入我的main.ts
我在那里进行应用程序的引导,如下所示:
import {provide, enableProdMode} from 'angular2/core';
import {bootstrap} from 'angular2/platform/browser';
import {ROUTER_PROVIDERS} from 'angular2/router';
import {APP_BASE_HREF} from 'angular2/platform/common';
import {HTTP_PROVIDERS, Http} from 'angular2/http';
import {AuthHttp, AuthConfig} from 'angular2-jwt';
import { User } from '../shared/models/user.model';
import {AppComponent} from './app/components/app.component';
if ('<%= ENV %>' === 'prod') { enableProdMode(); }
bootstrap(AppComponent, [
ROUTER_PROVIDERS,
provide(AuthHttp, {
useFactory: (http: any) => {
return new AuthHttp(new AuthConfig({
headerName: 'Authorization',
headerPrefix: 'Bearer',
tokenName: 'auth_token',
globalHeaders: [{'Content-Type':'application/json'}],
noJwtError: true,
noTokenScheme: true
}), http);
},
deps: [Http]
}),
provide(User, {useClass: User}),
provide(APP_BASE_HREF, { useValue: '<%= APP_BASE %>' })
]);
这很好用。然后我写了一个AuthService
来调用我的后端并处理登录/注销和JWT的存储。在这里,我想使用AuthHttp
提供商。正如我在文档中所读到的:当我在根级别注入一个提供服务时,Angular知道如何在另一个地方使用它时(在另一个服务中意味着)。但是我收到cannot find name authHttp
错误。
我的AuthService
看起来像这样:
import { Headers } from 'angular2/http';
import { Router } from 'angular2/router';
import { Injectable } from 'angular2/core';
import { JwtHelper } from 'angular2-jwt';
@Injectable()
export class AuthService {
token: any;
jwtHelper: JwtHelper = new JwtHelper();
constructor(private router: Router, private authHttp: AuthHttp, private user: User) {}
saveJwt(jwt: any) {
if(jwt) {
localStorage.setItem('auth_token', jwt);
this.token = localStorage.getItem('auth_token');
}
}
deleteJwt() {
localStorage.removeItem('auth_token');
this.token = localStorage.getItem('auth_token');
}
isAuth() {
var decoded: any;
decoded = this.jwtHelper.decodeToken(this.token);
var date = new Date(0);
date.setUTCSeconds(decoded.exp);
if(date === null) {
return false;
}
return (date.valueOf() > (new Date(0).valueOf()));
}
login(user: User) {
var header = new Headers();
header.append('Content-Type', 'application/json');
return this.authHttp.post('http://localhost:4000/sessions', JSON.stringify({ email: user.email, password: user.password }), {
headers: header
})
.map(res => res.json())
.subscribe(
data => {
console.log('Logged id');
this.saveJwt(data.auth_token);
},
err => console.log(err),
() => this.router.navigate(['Home'])
);
}
logout() {
this.deleteJwt();
this.router.navigate(['Home']);
}
}
然后我在AuthService
中使用LoginComponent
。像这样:
import { Component } from 'angular2/core';
import { COMMON_DIRECTIVES } from 'angular2/common';
import { AuthService } from '../shared/services/auth.service';
import { User } from '../shared/models/user.model';
@Component ({
selector: 'login',
moduleId: module.id,
directives: [COMMON_DIRECTIVES],
providers: [AuthService],
templateUrl: './login.component.html',
styleUrls: ['./login.component.css'],
})
export class LoginComponent {
constructor(
public auth: AuthService,
public user: User
) {}
submitted = false;
onSubmit() {
this.submitted = true;
this.auth.login(this.user);
console.log(JSON.stringify(this.user));
}
// TODO: Remove when done
get diagnostic() { return JSON.stringify(this.user); }
}
答案 0 :(得分:0)
您还需要将AuthService
添加到提供商
bootstrap(AppComponent, [
ROUTER_PROVIDERS,
provide(AuthHttp, {
useFactory: (http: any) => {
return new AuthHttp(new AuthConfig({
headerName: 'Authorization',
headerPrefix: 'Bearer',
tokenName: 'auth_token',
globalHeaders: [{'Content-Type':'application/json'}],
noJwtError: true,
noTokenScheme: true
}), http);
},
deps: [Http]
}),
provide(User, {useClass: User}),
provide(APP_BASE_HREF, { useValue: '<%= APP_BASE %>' }),
AuthService
]);