简体   繁体   中英

Unable to get value of service in @CanActivate decorator in component

I am using Angular 2.0.0-beta.15. I am trying to use @CanActivate in the component. Below is the piece of code.

@CanActivate((next: ComponentInstruction, previous: ComponentInstruction) =>  { 
console.log('loggedIn:' + isLoggedIn(next, previous));
console.log('isExists:' + isExists(next, previous))
})export class ParentLandingComponent {}

Now relevant piece of code in isExists.ts is as below:

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;
        }
     });
};

I have added the following in boot.ts as well.

///<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);
});

When i running, I am getting value of isExists(next, previous) in @CanAnnotation as undefined instead of boolean value. Inside isExists.ts, I am getting correct value as result. But when i am passing boolean value based on value of result, I am getting undefined on annotation portion.Can anyone help me to know what could be the issue in this?

The lambda in CanActivate() annotation has to return boolean|Promise<boolean> . Based on your code it's not returning anything. I am guessing you will return the value from isExists() . But, also isExists() doesn't return anything that's why it's undefined . I see you are trying to return true/false from the subscribe method. But that return is asynchronous and will not be resolved as you intended.

I suggest you convert your Observable to Promise<boolean> and return it from isExists()

relevant part in 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 {}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM