【发布时间】:2016-07-11 20:34:00
【问题描述】:
在 Angular2 中,我如何获取 GET 参数并将其存储在本地,就像在 Php 中的会话中一样?
在继续导航到调用安全 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