【问题标题】:How to get GET Params in Angular2 app?如何在 Angular2 应用程序中获取 GET 参数?
【发布时间】:2016-07-11 20:34:00
【问题描述】:

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

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

在继续导航到调用安全 Rest Web 服务的仪表板组件之前,我需要获取 access_token。 (需要令牌)

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

实际上我得到一个“例外:无法解析'RouteParams'(?)的所有参数。确保所有参数都用Inject装饰或具有有效的类型注释,并且'RouteParams'用Injectable装饰” 此应用程序启动后。

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:疏忽错误,新 main.ts : (这次只有一个引导程序>

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(…)

【问题讨论】:

  • this.token2 = _routeParams.get('access_token');这部分:)
  • 您在bootstrap() 中是否也有这些提供程序,或者仅在您的根组件`, directives: [ROUTER_DIRECTIVES], providers: [ ROUTER_PROVIDERS, HTTP_PROVIDERS, HeroService, RouteParams ] }) 上?
  • 我有:bootstrap(AppComponent, [HTTP_PROVIDERS]);在我的 main.ts 但即使使用: bootstrap(AppComponent, [HTTP_PROVIDERS,ROUTER_PROVIDERS]);我有同样的错误:/
  • 您实际上没有两个bootstrap(AppComponent) 行,如您的问题中所示? (编辑:1),你呢?

标签: angular typescript


【解决方案1】:

已弃用路由器的更新

仅在 bootstrap() 或仅在 AppComponent 中添加这些提供程序

bootstrap(AppComponent, [
    ROUTER_PROVIDERS,
    HTTP_PROVIDERS])

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

还要确保RouteParamsROUTER_PROVIDERS 是从angular2/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 like 并访问类似的值

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

【讨论】:

  • 我做到了。同样的错误,从“angular2/router”导入{ROUTER_PROVIDERS, RouteParams};在“main.ts”文件中
猜你喜欢
  • 2018-04-05
  • 2018-04-19
  • 2010-11-17
  • 2017-03-11
  • 2016-12-12
  • 1970-01-01
  • 1970-01-01
  • 2012-08-04
  • 1970-01-01
相关资源
最近更新 更多