我正在使用Angular 2.0.0-beta.15。我试图在组件中使用@CanActivate。下面是一段代码。
@CanActivate((next: ComponentInstruction, previous: ComponentInstruction) => {
console.log('loggedIn:' + isLoggedIn(next, previous));
console.log('isExists:' + isExists(next, previous))
})export class ParentLandingComponent {}
现在isExists.ts中的相关代码如下:
import {Injector} from 'angular2/core';
import {appInjector} from './app-injector';
import {DataService} from '../services/data-services.service';
export const isExists = (next: ComponentInstruction, previous: ComponentInstruction) => {
let injector: Injector = appInjector();
let userService: UserService = injector.get(UserService);
let router: Router = injector.get(Router);
let cookieService: CookieService = injector.resolveAndInstantiate(CookieService);
dataService.isExists().subscribe(result => {
console.log('isExists:' + result);
if (result) {
console.log('result:' + result);
cookieService.removeAll();
router.navigate(['Login']);
return true;
} else {
return false;
}
});
};
我也在boot.ts中添加了以下内容。
///<reference path="../../node_modules/angular2/typings/browser.d.ts"/>
import {bootstrap} from 'angular2/platform/browser';
import {provide} from 'angular2/core';
import {ROUTER_PROVIDERS, ROUTER_DIRECTIVES, RouteConfig, Location, LocationStrategy, HashLocationStrategy} from 'angular2/router';
import {AppComponent} from './app.component';
import {HTTP_PROVIDERS} from 'angular2/http';
import 'rxjs/Rx';
import {DataService} from './services/data-services.service';
import {StateService} from './services/current-user-state.service';
import {appInjector} from './utils/app-injector';
import {HttpClient} from './services/http-client.service';
bootstrap(AppComponent, [DataService, StateService, HttpClient, ROUTER_PROVIDERS, HTTP_PROVIDERS,
provide(LocationStrategy, { useClass: HashLocationStrategy })])
.then(appRef => {
appInjector(appRef.injector);
});
当我运行时,我在@CanAnnotation中获得isExists(next,previous)的值为undefined而不是boolean值。在isExists.ts里面,我得到了正确的值。但是当我根据结果的值传递布尔值时,我在注释部分得到了未定义。任何人都可以帮助我知道这可能是什么问题?
答案 0 :(得分:1)
CanActivate()
注释中的lambda必须返回boolean|Promise<boolean>
。根据您的代码,它没有返回任何内容。我猜你会从isExists()
返回值。但是,isExists()
也不会返回任何与其undefined
相关的内容。我看到你试图从subscribe方法返回true/false
。但该返回是异步的,不会按预期解决。
我建议您将Observable
转换为Promise<boolean>
并将其从isExists()
isExists()中的相关部分:
return dataService.isExists().map(result => { // change subscribe to 'map' in order to change the return type of the observable and do the other stuff
console.log('isExists:' + result);
if (result) {
console.log('result:' + result);
cookieService.removeAll();
router.navigate(['Login']);
return true;
} else {
return false;
}
}).toPromise();
@CanActivate():
@CanActivate((next: ComponentInstruction, previous: ComponentInstruction) => {
console.log('loggedIn:' + isLoggedIn(next, previous));
return isExists(next, previous);
})
export class ParentLandingComponent {}