2016-09-02 3 views
1

Я пытаюсь реализовать вход в систему и зарегистрироваться с Auth0. Я последовал за эти действия с сайта Auth0:Angular 2 - Auth0

https://auth0.com/docs/quickstart/spa/angular2/01-login

Я использую Угловые 2 RC5

Это как мои файлы выглядят следующим образом:

app.component.html

<div class="navbar-header"> 
<a class="navbar-brand" href="#">Auth0 - Angular 2</a> 
<button class="btn btn-primary btn-margin" (click)="auth.login()" *ngIf="!auth.authenticated()">Log In</button> 
<button class="btn btn-primary btn-margin" (click)="auth.logout()" *ngIf="auth.authenticated()">Log Out</button> 
</div> 

app.component.ts

импорт { Компонент} из '@ angular/core'; import {Auth} из "./auth.service";

@Component({ 
selector: 'app-root', 
templateUrl: './app.component.html', 
styleUrls: ['./app.component.css'], 
}) 
export class AppComponent { 
constructor(private auth: Auth) {} 
} 

auth.service.ts

import { Injectable }  from '@angular/core'; 
import { tokenNotExpired } from 'angular2-jwt'; 

// Avoid name not found warnings 
declare var Auth0Lock: any; 

@Injectable() 
export class Auth { 
    // Configure Auth0 
    lock = new Auth0Lock('MY_CLIENT_ID', 'MY_DOMAIN.auth0.com', {}); 

    constructor() { 
    // Add callback for lock `authenticated` event 
    this.lock.on("authenticated", (authResult) => { 
     localStorage.setItem('id_token', authResult.idToken); 
    }); 
    } 

    public login() { 
    // Call the show method to display the widget. 
    this.lock.show(); 
    }; 

    public authenticated() { 
    // Check if there's an unexpired JWT 
    // This searches for an item in localStorage with key == 'id_token' 
    return tokenNotExpired(); 
    }; 

    public logout() { 
    // Remove token from localStorage 
    localStorage.removeItem('id_token'); 
    }; 
} 

Но я получаю эти ошибки в моем Chrome Developer JavaScript консоли:

EXCEPTION: Error in ./AppComponent class AppComponent_Host - inline template:0:0 
EXCEPTION: Error in ./AppComponent class AppComponent_Host - inline template:0:0 
ORIGINAL EXCEPTION: No provider for Auth! 
ORIGINAL STACKTRACE: 
Error: DI Exception 
    at NoProviderError.BaseException [as constructor] (exceptions.js:27) 
    at NoProviderError.AbstractProviderError [as constructor] (reflective_exceptions.js:43) 
    at new NoProviderError (reflective_exceptions.js:80) 
    at ReflectiveInjector_._throwOrNull (reflective_injector.js:786) 
    at ReflectiveInjector_._getByKeyDefault (reflective_injector.js:814) 
    at ReflectiveInjector_._getByKey (reflective_injector.js:777) 
    at ReflectiveInjector_.get (reflective_injector.js:586) 
    at NgModuleInjector.get (ng_module_factory.js:98) 
    at DebugAppView._View_AppComponent_Host0.createInternal (AppComponent.ngfactory.js:16) 
    at DebugAppView.AppView.create (view.js:101) 
ERROR CONTEXT: 
DebugContext {_view: _View_AppComponent_Host0, _nodeIndex: 0, _tplRow: 0, _tplCol: 0}_nodeIndex: 0_staticNodeInfo: (...)_tplCol: 0_tplRow: 0_view: _View_AppComponent_Host0component: (...)componentRenderElement: (...)context: (...)injector: (...)providerTokens: (...)references: (...)renderNode: (...)source: (...)__proto__: Object 
Unhandled Promise rejection: EXCEPTION: Error in ./AppComponent class AppComponent_Host - inline template:0:0 
ORIGINAL EXCEPTION: No provider for Auth! 
ORIGINAL STACKTRACE: 
Error: DI Exception 
    at NoProviderError.BaseException [as constructor] (http://localhost:4200/main.bundle.js:1867:23) 
    at NoProviderError.AbstractProviderError [as constructor] (http://localhost:4200/main.bundle.js:29230:16) 
    at new NoProviderError (http://localhost:4200/main.bundle.js:29267:16) 
    at ReflectiveInjector_._throwOrNull (http://localhost:4200/main.bundle.js:58584:19) 
    at ReflectiveInjector_._getByKeyDefault (http://localhost:4200/main.bundle.js:58612:25) 
    at ReflectiveInjector_._getByKey (http://localhost:4200/main.bundle.js:58575:25) 
    at ReflectiveInjector_.get (http://localhost:4200/main.bundle.js:58384:21) 
    at NgModuleInjector.get (http://localhost:4200/main.bundle.js:42059:52) 
    at DebugAppView._View_AppComponent_Host0.createInternal (AppComponent.ngfactory.js:16:70) 
    at DebugAppView.AppView.create (http://localhost:4200/main.bundle.js:59148:21) 
ERROR CONTEXT: 
[object Object] ; Zone: <root> ; Task: Promise.then ; Value: ViewWrappedException {_wrapperMessage: "Error in ./AppComponent class AppComponent_Host - inline template:0:0", _originalException: NoProviderError, _originalStack: "Error: DI Exception↵ at NoProviderError.BaseExc…e (http://localhost:4200/main.bundle.js:59148:21)", _context: DebugContext, _wrapperStack: "Error: Error in ./AppComponent class AppComponent_… at http://localhost:4200/main.bundle.js:27889:27"} 
Error: Uncaught (in promise): EXCEPTION: Error in ./AppComponent class AppComponent_Host - inline template:0:0(…) 

и веб-страница является пустым. Ничего не появляется.

Любая помощь была бы принята с благодарностью.

Приветствия,

метаданные

ответ

0

Внутри компонентов, добавьте: -

providers: [Auth] 

Using services

Или: -

Включите его в метаданных ngModule: -

import { NgModule }  from '@angular/core'; 
import { BrowserModule } from '@angular/platform-browser'; 
import {Auth} from 'your path' 
@NgModule({ 
    imports: [ 
    //your imports 
], 

bootstrap: [//your component], 
providers: [Auth] 

})

Refer here

+0

Я пробовал это раньше, к сожалению, он не работал –

+0

попробуйте предоставить сервис в метаданных ngModule –

+0

Нет, я все равно получаю ту же ошибку –

0

шаги не упоминает, но вам нужно добавить следующий сценарий в вашем index.html.

<script src="http://cdn.auth0.com/js/lock/10.2/lock.min.js"></script> 

Когда я сделал этот сайт начал загружаться, теперь я получаю другую ошибку.

core.umd.js e2a5: 3462 ИСКЛЮЧЕНИЕ: Ошибка в ./AppComponent класса AppComponent - встроенный шаблон: 4: 70 вызвано следующими причинами: Не удается прочитать свойство «аутентификацией» неопределенных

Я буду держать вас в курсе, если Я могу это решить.

+0

Я получил ее работу, я дал другое имя (вместо auth, я дал аутентификацию) в конструкторе компонента. моя глухая ошибка стоила мне полчаса. constructor (private api: ApiService, private auth: Auth) {...} –

2

Это, как я реализовал, и это работает отлично Код защиты

app.module.ts

import { AUTH_PROVIDERS } from 'angular2-jwt'; 
import { Auth } from './services/auth0.service'; 


    @NgModule({ 
     declarations: [ 
     AppComponent 
     ], 
     imports: [ 
     BrowserModule, 
     FormsModule, 
     HttpModule 
     ], 
     providers: [AUTH_PROVIDERS, Auth], 
     bootstrap: [AppComponent] 
    }) 
    export class AppModule { } 

индекс.HTML

<!doctype html> 
<html> 
<head> 
    <meta charset="utf-8"> 
    <title>Angular2Auth0</title> 
    <base href="/"> 

    <meta name="viewport" content="width=device-width, initial-scale=1"> 
    <link rel="icon" type="image/x-icon" href="favicon.ico"> 
    <script src="http://cdn.auth0.com/js/lock/10.2/lock.min.js"></script> 
</head> 
<body> 
    <app-root>Loading...</app-root> 
</body> 
</html> 

app.component.ts

import { Component } from '@angular/core'; 
import { Auth } from './services/auth0.service'; 

@Component({ 
    selector: 'app-root', 
    templateUrl: './app.component.html', 
    styleUrls: ['./app.component.css'] 
}) 

export class AppComponent { 

    constructor(private auth: Auth) { 
    console.log(auth); 
    } 


} 
+0

Вот пример кода для того же https://github.com/MateenKadwaikar/Angular2Auth0GoogleMap –

1

Это работает для меня:

`импорт {инъекционные} от '@ угловой/ядро'; import {Router, CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot} из '@ angle/router';

@Injectable() экспорт класс AuthGuard реализует CanActivate {

constructor(private router: Router) { } 

public canActivate(route: ActivatedRouteSnapshot, state: `enter code here`RouterStateSnapshot) { 
    if (localStorage.getItem('userId')) { 
     return true; 
    } 

    // not logged in so redirect to login page with the return url 
    this.router.navigate(['/login'], { queryParams: { returnUrl: state.url } }); 
    return false; 
} 

} `

Используйте этот маршрутизатор: export const ROUTES: Routes = [ { path: '', component: YourComponent, canActivate: [AuthGuard]} ];

И логин установить локальное хранилище: localStorage.setItem('userId', id);

Смежные вопросы