如何在Angular2应用程序中获取GET Params?

时间:2016-03-24 09:38:56

标签: angular typescript

在Angular2中,我如何获得GET参数并将其存储在本地,就像在Php中的会话一样?

http://localhost:8080/contextPath/index.html?login=true#token_type=Bearer&expires_in=9999&access_token=xxxXXXXXxxx

我需要获取access_token才能继续导航到调用安全的Rest Webservice的dashBoard组件。 (需要令牌)

@Component({
 selector: 'my-app',
 template: `
 <h1>{{title}}</h1>
  <nav>
    <a [routerLink]="['Dashboard']">Dashboard</a>
    <a [routerLink]="['Heroes']">Heroes</a>
  </nav>
  <router-outlet></router-outlet>
  `,
    directives: [ROUTER_DIRECTIVES],
    providers: [
        ROUTER_PROVIDERS,
        HTTP_PROVIDERS,
        HeroService,
        RouteParams
    ]
})
@RouteConfig([
    {
        path: '/heroes',
        name: 'Heroes',
        component: HeroesComponent
    },
    {
        path: '/dashboard',
        name: 'Dashboard',
        component: DashboardComponent,
        useAsDefault: true
    },
    {
        path: '/getHero/:id',
        name: 'HeroDetail',
        component: HeroDetailComponent
    },
])
export class AppComponent {
    title = 'Tour of Heroes';
    private token2;

    constructor(
        private _routeParams:RouteParams) {

        this.token2 = _routeParams.get('access_token');
        console.log("token from Url : "+ this.token2);
    }
}

实际上我得到了一个&#34; EXCEPTION:无法解析&#39; RouteParams&#39;(?)的所有参数。确保所有参数都使用Inject进行修饰或具有有效的类型注释以及&#39; RouteParams&#39;用Injectable&#34;装饰 在这个应用程序发布后。

hero.service.ts:

@Injectable()
export class HeroService {
    ot: Observable<string>;
private token2 =  'test';

private serviceUrl = 'http://localhost:8080/Context_Path/';
private token = "xXXXX";
private headers = new Headers();

constructor(private http:Http){
    this.headers.append('Authorization', 'bearer '+ this.token);
    this.headers.append('Content-Type', 'application/json');
}
//Renvois maintenant un observable sur lequel un composant doit s'incrire
getHeroes() {

    var opUrl = 'getHeroes.json';
    //appel asynchrone comme pour un serveur http
    //return Promise.resolve(HEROES);
    //return HEROES;
    //Recuperation des heros façon rest via fed
    return this.http.get(this.serviceUrl + opUrl,{
            headers: this.headers
        })
        //mise en relation du json retourné et d'un tableau de hero
        .map(res => <Hero[]> res.json())
        //TODO[PROD] commenter avant la mise en prod
        .do(data => console.log(data)) // eyeball results in the console
        .catch(this.handleError);
}
getHero(id:number) {
    var opUrl = 'getHero.json?id='+id;
    return this.http.get(this.serviceUrl + opUrl,{
            headers: this.headers
        })
        //TODO[PROD] commenter avant la mise en prod
        .do(data => console.log(data)) // eyeball results in the console
        .catch(this.handleError);

}
private handleError (error: Response) {
    // in a real world app, we may send the error to some remote logging infrastructure
    // instead of just logging it to the console
    console.error(error);
    return Observable.throw(error.json().error || 'Server error');
}
//pour verifier le comportement d'un gros temps de réponse
getHeroesSlowly() {
    return new Promise<Hero[]>(resolve =>
        setTimeout(()=>resolve(HEROES), 2000) // 2 seconds
    );
}
}

Dashborad.component.ts:

import { Component, OnInit } from 'angular2/core';
import { Hero } from './hero';
import { HeroService } from './hero.service';
import { Router } from 'angular2/router';

@Component({
    selector: 'my-dashboard',
    templateUrl: 'app/dashboard.component.html',
})
export class DashboardComponent implements OnInit {
    heroes: Hero[] = [];
    private errorMessage;

    constructor(
        private _router: Router,
        private _heroService: HeroService) {
    }

    ngOnInit() {
        this._heroService.getHeroes()
            .subscribe(heroes => this.heroes = heroes,
                error => this.errorMessage = <any>error);
    }
    gotoDetail(hero: Hero) {
        let link = ['HeroDetail', { id: hero.id }];
        this._router.navigate(link);
    }
}

编辑:1在消化后我将main.ts修改为:

bootstrap(AppComponent);
bootstrap(AppComponent, [ROUTER_PROVIDERS,HTTP_PROVIDERS,RouteParams]);

并删除了app.components.ts中的提供商

但是出现了错误:

Cannot resolve all parameters for 'RouteParams'(?). Make sure that all the parameters are decorated with Inject or have valid type annotations and that 'RouteParams' is decorated with Injectable.
angular2-polyfills.js:322 Error: TypeError: Cannot read property 'getOptional' of undefined(…)ZoneDelegate.invoke @ angular2-polyfills.js:322Zone.run @ angular2-polyfills.js:218(anonymous function) @ angular2-polyfills.js:567ZoneDelegate.invokeTask @ angular2-polyfills.js:355Zone.runTask @ angular2-polyfills.js:254drainMicroTaskQueue @ angular2-polyfills.js:473ZoneTask.invoke @ angular2-polyfills.js:425
angular2.dev.js:23740 EXCEPTION: No provider for RouteParams! (AppComponent -> RouteParams)

编辑2:Inatention错误,新的main.ts: (这次只有一个bootstrap&gt;&lt;)

bootstrap(AppComponent, [ROUTER_PROVIDERS,HTTP_PROVIDERS,RouteParams]);

现在只有这个错误:

Cannot resolve all parameters for 'RouteParams'(?). Make sure that all the parameters are decorated with Inject or have valid type annotations and that 'RouteParams' is decorated with Injectable.
angular2-polyfills.js:322 Error: TypeError: Cannot read property 'getOptional' of undefined(…)

1 个答案:

答案 0 :(得分:2)

弃用路由器的更新

仅在bootstrap()或仅AppComponent

中添加这些提供商
bootstrap(AppComponent, [
    ROUTER_PROVIDERS,
    HTTP_PROVIDERS])

并在其他地方删除它们。如果应该与整个应用程序共享,则不需要多次提供相同的提供程序。

同时确保从RouteParams导入ROUTER_PROVIDERSangular2/router。它们不会由angular2/core导出。

另请参阅我对How to get GET paramater in Angular2?

的回答

在根组件中,您可以注入路由器并订阅路由事件,然后从路由器获取参数

export class AppComponent {
  constructor(private router:Router) {
    router.subscribe(route => {
      console.debug(this.router.currentInstruction.component.params);
    });
  }
}

在路由器添加的组件上,您可以注入RouteParams之类的内容,并访问

等值
export class Other{
    constructor(private routeParams: RouteParams) {
    console.debug(this.routeParams);
    console.log(this.routeParams.get('filter_industry'));
    console.log(this.routeParams.get('filter_start_with'));
  }
}

Plunker example