Javascript 角度2-0
我正在尝试实现登录并从Auth0注册。我在Auth0网站上遵循了以下步骤: 我使用的是角2 RC5 以下是我的文件的外观: app.component.htmlJavascript 角度2-0,javascript,node.js,angular,auth0,Javascript,Node.js,Angular,Auth0,我正在尝试实现登录并从Auth0注册。我在Auth0网站上遵循了以下步骤: 我使用的是角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
<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>
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(…)
异常:./AppComponent类AppComponent\u主机中出错-内联模板:0:0
异常:./AppComponent类AppComponent_主机中出错-内联模板:0:0
原始异常:没有身份验证的提供程序!
原始堆栈跟踪:
错误:DI异常
在NoProviderError.BaseException[作为构造函数](exceptions.js:27)
在NoProviderError.AbstractProviderError[作为构造函数](reflective_exceptions.js:43)
在新的NoProviderError(reflective_exceptions.js:80)
在ReflectiveInjector_u.\u throwOrNull处(ReflectiveInjector.js:786)
在ReflectiveInjector_u.\u getByKeyDefault(reflective_injector.js:814)处
在ReflectiveInjector_u.\u getByKey(ReflectiveInjector.js:777)处
在ReflectiveInjector.get处(ReflectiveInjector.js:586)
在NgModuleInjector.get(ng_module_factory.js:98)
在DebugAppView.\u View\u AppComponent\u Host0.createInternal(AppComponent.ngfactory.js:16)
在DebugAppView.AppView.create(view.js:101)上
错误上下文:
DebugContext{u view:{u view:{u AppComponent}u Host0,{u nodeIndex:0,{u tplRow:0,}{u nodeIndex:0}{u staticNodeInfo:(…)\u tplRow:0}视图:{u AppComponent\u Host0组件:(…)组件渲染:(…)上下文:(…)注入器:(…)providerTokens:(…)引用:(…)渲染节点:(…)源:(…)\uUu:
未处理的承诺拒绝:异常:./AppComponent类AppComponent\u主机中出错-内联模板:0:0
原始异常:没有身份验证的提供程序!
原始堆栈跟踪:
错误:DI异常
在NoProviderError.BaseException[作为构造函数](http://localhost:4200/main.bundle.js:1867:23)
在NoProviderError.AbstractProviderError[作为构造函数](http://localhost:4200/main.bundle.js:29230:16)
在new NoProviderError(http://localhost:4200/main.bundle.js:29267:16)
在ReflectiveInjector_u.u throwOrNull处(http://localhost:4200/main.bundle.js:58584:19)
在ReflectiveInjector_u.\u getByKeyDefault(http://localhost:4200/main.bundle.js:58612:25)
在ReflectiveInjector_u.\u getByKey(http://localhost:4200/main.bundle.js:58575:25)
在ReflectiveInjector_2;,获取(http://localhost:4200/main.bundle.js:58384:21)
在NgModuleInjector.get(http://localhost:4200/main.bundle.js:42059:52)
在DebugAppView.\u View\u AppComponent\u Host0.createInternal(AppComponent.ngfactory.js:16:70)
在DebugAppView.AppView.create上(http://localhost:4200/main.bundle.js:59148:21)
错误上下文:
[对象];区域:;任务:承诺;值:ViewWrappedException{U wrapperMessage:“./AppComponent类AppComponent\U主机-内联模板:0:0”中的错误,_originalException:NoProviderError,_originalStack:“错误:DI异常”↵ 在没有提供错误。BaseExc…e(http://localhost:4200/main.bundle.js:59148:21)“,_context:DebugContext,_wrapperStack:”错误:在./AppComponent类AppComponent中出错http://localhost:4200/main.bundle.js:27889:27"}
错误:未捕获(承诺中):异常:./AppComponent类AppComponent_主机中的错误-内联模板:0:0(…)
网页是空白的。什么也没有出现
任何帮助都将不胜感激
干杯,在组件元数据中,添加:-
providers: [Auth]
或:-
将其包含在您的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]
})
这些步骤没有提及,但您需要在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中的错误,原因是:无法读取未定义的属性“authenticated”
如果我能解决这个问题,我会及时通知你。这就是我如何实现的,它运行良好,代码极客 应用程序模块.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 { }
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);
}
}
index.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>
这对我很有用:
`从“@angular/core”导入{Injectable};
从'@angular/Router'导入{Router,CanActivate,ActivatedRouteSnapshot,RouterStateSnashot}
@可注射()
导出类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;
}
}`
在路由器中使用此选项:
导出常量路由:路由=[
{路径:'',组件:YourComponent,canActivate:[AuthGuard]}
];代码>
并在登录设置本地存储:
localStorage.setItem('userId',id)代码>我让它工作了,我在组件构造函数中指定了一个不同的名称(而不是auth,我指定了authenticated)。愚蠢的错误浪费了我半个小时。构造函数(private-api:ApiService,private-auth:auth){…}下面是相同的示例代码
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;
}