auth0 / angular2-jwt

Helper library for handling JWTs in Angular apps
MIT License
2.63k stars 485 forks source link

when i use get() in angular2,it get null,and return a Observable error to me #213

Closed clp334264003 closed 8 years ago

clp334264003 commented 8 years ago

1、 login (credentials, callback?) { var cb = callback || function(){};

    return new Promise((resolve, reject) => {
        this.authServerProvider.login(credentials).subscribe(data => {
            this.principal.identity(true).then(account => {
                console.log("account:"+account);
                resolve(data);
            });
            return cb();
        }, err => {
            this.logout();
            reject(err);
            return cb(err);
        });
    });
}

2、 identity (force?: boolean): Promise { if (force === true) { this._identity = undefined; }

    // check and see if we have retrieved the _identity data from the server.
    // if we have, reuse it by immediately resolving
    if (this._identity) {
        return Promise.resolve(this._identity);
    }

    // retrieve the _identity data from the server, update the _identity object, and then resolve.
    return this.account.get().toPromise().then(account => {
        if (account) {
            this._identity = account;
            this.authenticated = true;
        } else {
            this._identity = null;
            this.authenticated = false;
        }
        return this._identity;
    }).catch(err => {
        this._identity = null;
        this.authenticated = false;
        return null;
    });
}

3、 import {AuthHttp} from '../http/index';

@Injectable() export class AccountService { constructor(public authHttp:AuthHttp) { }

get(): Observable<any> {
  return this.authHttp.get(MockCfg.baseUrl+MockCfg.accountUrl );
}

save(account: any): Observable<Response> {
    return this.authHttp.post(MockCfg.baseUrl+MockCfg.accountUrl, account);
}

} 4、

import { Injectable } from '@angular/core'; import { Request, Response, RequestOptionsArgs } from '@angular/http'; import { Router } from '@angular/router'; import { AuthHttp as JwtAuthHttp} from 'angular2-jwt'; import { Observable } from 'rxjs/Observable'; import 'rxjs/add/operator/share';

@Injectable() export class AuthHttp {

constructor(private authHttp: JwtAuthHttp, private router: Router) { }

private isUnauthorized(status: number): boolean { return !status || status === 401 || status === 403; }

private handleError (error: any) { // In a real world app, we might use a remote logging infrastructure // We'd also dig deeper into the error to get a better message console.log(error); if(error.message) { return Observable.throw({message:error.message,status:error.status}); }

let message :string= null;
if(error._body) {
  try{
    let body = JSON.parse(error._body);
    message = body.message||body.error;
  }catch(e){;}
}
let errMsg = (message) ? message :
  error.status ? `${error.status} - ${error.statusText}` : 'Server error';
console.error(errMsg); // log to console instead
return Observable.throw({message:errMsg,status:error.status});

}

private authIntercept(response: Observable){ var sharableResponse = response.share(); sharableResponse.subscribe(null, (err) => { if (this.isUnauthorized(err.status)) { this.router.navigate(['/login']); } // Other error handling may be added here, such as refresh token … }); return sharableResponse.map(res=>{ try{return res.json();} catch(e){return res;} }).catch(this.handleError);

}

public request(url: string | Request, options?: RequestOptionsArgs): Observable { return this.authIntercept(this.authHttp.request(url, options)); }

public get(url: string, options?: RequestOptionsArgs): Observable { return this.authIntercept(this.authHttp.get(url, options)); }

public post(url: string, body: any, options?: RequestOptionsArgs): Observable { return this.authIntercept(this.authHttp.post(url, body,options)); }

public put(url: string, body: any, options?: RequestOptionsArgs): Observable { return this.authIntercept(this.authHttp.put(url, body, options)); }

public delete(url: string, options?: RequestOptionsArgs): Observable { return this.authIntercept(this.authHttp.delete(url, options)); }

public patch(url: string, body: any, options?: RequestOptionsArgs): Observable { return this.authIntercept(this.authHttp.patch(url, body, options)); }

public head(url: string, options?: RequestOptionsArgs): Observable { return this.authIntercept(this.authHttp.head(url, options)); }

public options(url: string, options?: RequestOptionsArgs): Observable { return this.authIntercept(this.authHttp.options(url, options)); } }

clp334264003 commented 8 years ago

app.module.ts import { NgModule } from '@angular/core'; import { BrowserModule } from '@angular/platform-browser'; import { APP_BASE_HREF } from '@angular/common'; import { RouterModule } from '@angular/router'; import { HttpModule } from '@angular/http'; import { AppComponent } from './app.component'; import { routes } from './app.routes';

import { SharedModule } from './shared/shared.module'; import { SideBaComponentModule } from './policy/sidebar/index'; import { HeaderMenuModule } from './header/index'; import { HomeComponentModule } from './home/index'; import { PolicyComponentModule } from './policy/index'; import { SocialCircleComponentModule } from './socialCircle/index'; import { AnalysisComponentModule } from './analysis/index'; import { InformationComponentModule } from './information/index'; import { PlatformMarketComponentModule } from './platformMarket/index'; import { MoreComponentModule } from './more/index'; import { LoginComponentModule } from './login/index'; import { registerComponentModule } from './register/index'; import { AUTH_PROVIDERS,provideAuth } from 'angular2-jwt'; import { AuthHttp } from './shared/http/auth-http.service'; @NgModule({ imports: [BrowserModule, HttpModule, RouterModule.forRoot(routes), SharedModule.forRoot() ,HeaderMenuModule ,HomeComponentModule ,PolicyComponentModule ,SocialCircleComponentModule ,AnalysisComponentModule ,InformationComponentModule ,PlatformMarketComponentModule ,MoreComponentModule ,LoginComponentModule ,SideBaComponentModule ,registerComponentModule ], declarations: [AppComponent],

providers: [ AUTH_PROVIDERS, AuthHttp, provideAuth({ headerName: "authorization", headerPrefix: "Bearer", tokenName: "id_token", tokenGetter: (() => window.localStorage.getItem('authenticationToken')), globalHeaders: [{'Content-Type':'application/json'}], noJwtError: false, noTokenScheme: false }), { provide: APP_BASE_HREF, useValue: '<%= APP_BASE %>' }, ], bootstrap: [AppComponent] })

export class AppModule { }

clp334264003 commented 8 years ago

package.json "dependencies": { "@angular/common": "^2.1.0", "@angular/compiler": "^2.1.0", "@angular/core": "^2.1.0", "@angular/forms": "^2.1.0", "@angular/http": "^2.1.0", "@angular/material": "2.0.0-alpha.9-3", "@angular/platform-browser": "^2.1.0", "@angular/platform-browser-dynamic": "^2.1.0", "@angular/router": "^3.1.0", "angular2-cookie": "^1.2.2", "angular2-jwt": "^0.1.25", "bootstrap": "3.3.7", "core-js": "^2.4.1", "font-awesome": "4.6.3", "jquery": "3.1.0", "moment": "^2.13.0", "ng2-bootstrap": "1.1.3", "ng2-bs3-modal": "^0.8.1", "ng2-webstorage": "^1.3.3", "reflect-metadata": "^0.1.8", "rxjs": "5.0.0-beta.12", "systemjs": "0.19.39", "underscore": "^1.8.3", "zone.js": "0.6.25" }

clp334264003 commented 8 years ago

after login wo get a token ,but i can not use get()

clp334264003 commented 8 years ago

i have no way,thanks

escardin commented 8 years ago

Can you explain your situation more? I don't understand the problem and all I see is a ton of unrelated code to go through.

clp334264003 commented 8 years ago

how can i use angular2-jwt in angular-seed?

clp334264003 commented 8 years ago

Perhaps other errors, after all, I have access to the token