私は、Angular 2アプリの他の部分でルートレベルで注入されたプロバイダを使用する方法を理解する上で問題があります。角2:別のサービスでブートストラップ中に注入されたプロバイダを使用する方法?
私はJWT認証に役立つ工場提供者angular2-jwtを持っています。
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 %>' })
]);
これは正常に動作します:私はそうのようなアプリのブートストラップを行う私のmain.ts
に注入します。私は少し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']);
}
}
私はその後、LoginComponent
でAuthService
を使用しています。これと同じように:
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); }
}
問題が何であるかを完全にわかりません。エラーメッセージが表示されますか?どこでエラーが出ますか?あなたは何を達成しようとしていますか?あなたは 'AuthService'をどこに注入しますか? –
ブートストラップ中にAuthHttpを注入しています(上記参照)。私はAuthServiceでそれを使いたい。私が得るエラーは '名前 'AuthHttp'を見つけることができません。 ' –
しかし、あなたはどのようにAuthServiceを使いますか?あなたはプロバイダにそれを追加する必要があります(私の答えに示されているように)。 –