MFB*_*MFB 30 typescript angular2-routing
鉴于这个url结构(我无法控制),如何使用Angular2检索哈希片段?
http://your-redirect-uri#access_token=ACCESS-TOKEN
我的路由器确实路由到正确的组件,但是一切都oauth
被废弃后我无法在request.params或location.path中找到哈希片段.注定?
路由器配置:
@RouteConfig([
{path: '/welcome', name: 'Welcome', component: WelcomeComponent, useAsDefault: true},
{path: '/landing/oauth', name: 'Landing', component: LandingComponent} // this one
Run Code Online (Sandbox Code Playgroud)
])
Ism*_*l H 41
对于那些仍在寻找:
import { ActivatedRoute } from '@angular/router';
export class MyComponent {
constructor(
private route: ActivatedRoute,
) { }
myfunction(){
this.route.fragment.subscribe((fragment: string) => {
console.log("My hash fragment is here => ", fragment)
})
}
}
Run Code Online (Sandbox Code Playgroud)
nwa*_*yve 11
为了扩展当前的答案,我想解决一种简单的方法来解析哈希中的查询参数(特别是对于联合响应),因为ActivatedRoute
它似乎本身并不处理.
this.route.fragment.subscribe(fragment => {
const response = _.fromPairs(Array.from(new URLSearchParams(fragment)));
response.access_token;
response.id_token;
response.expires_in;
response.token_type;
});
Run Code Online (Sandbox Code Playgroud)
首先使用片段创建一个新的URLSearchParams对象以查询其值:
new URLSearchParams(fragment).get('access_token');
Run Code Online (Sandbox Code Playgroud)
对于大多数情况,这可能是所有需要的,但如果需要Array.from
将其转换URLSearchParams
为对象,则转换为数组数组,如下所示:[['key', 'value'], ...]
.然后lodash _.fromPairs
将其转换为对象.
小智 9
您还可以使用ActivatedRouteSnapshot而无需订阅其上的所有更改。
@Component({templateUrl:'./my-component.html'})
class MyComponent {
constructor(route: ActivatedRoute) {
const fragment: string = route.snapshot.fragment;
}
}
Run Code Online (Sandbox Code Playgroud)
我从 nwayve 那里得到了评论,并使用 RxJS 管道实现了它,如下所示:
this.route.fragment
.pipe(
map(fragment => new URLSearchParams(fragment)),
map(params => ({
access_token: params.get('access_token'),
id_token: params.get('id_token'),
error: params.get('error'),
}))
)
.subscribe(res => console.log('', res));
Run Code Online (Sandbox Code Playgroud)