2017-03-10 32 views
0

我正在尝试创建一个组件,该组件在激活的路由中订阅了id url参数,然后使用它来调用我的一个服务,该服务向该服务器发出一个http请求并使用该id。如何将订阅的url参数链接到服务中的订阅?

我有一个发生在一个id像这样的路线 - /文/图/ 1005

以前,我并没有订阅的URL参数,我只是从URL抓取ID一次。

这是在类的代码,然后:

ngOnInit() { 
    var id = +this.activatedRoute.snapshot.params["id"]; 

    if (id) { 
     this.articleService.get(id).subscribe(
      article => this.article = article 
     ); 
    } 
    else if (id === 0) { 
     console.log("id is 0: switching to edit mode..."); 
     this.router.navigate(["article/edit", 0]); 
    } 
    else { 
     console.log("Invalid id: routing back to home..."); 
     this.router.navigate([""]); 
    } 
} 

然而,我所遇到的,其中相同的组件可以被路由到反复,但与不同的ID,每次和ngOnInit挂钩的情况是只发射第一次。所以我想订阅url参数中的id来解决这个问题。

我试着找到一个解决方案,它看起来像一个平面地图是我想要使用的。不过,我不能找到一个很好的来源,显示了如何将一个订阅链接的URL参数,这样

this.activatedRoute.params.subscribe((params: Params) => { 
     id = params['id']; 
     console.log(params); 
    }) 

到订阅我的文章的服务。

+0

为其他组件获取的数据是一个子组件? – Aravind

+0

不,我只是在这个例子中有一个组件。它没有任何儿童组件。 – LayfieldK

回答

0

你可以使用路由解析如下

export const appRoutes: Routes = [ 
    ... 
    { 
    path: 'path1/:id', 
    component: YourComponent, 
    resolve: { 
     someObject: ComponentResolve 
    } 
    } 
]; 

@Injectable() 
export class ComponentResolve implements Resolve<Interface> { 

    constructor(private yourService: YourService) {} 

    resolve(route: ActivatedRouteSnapshot) { 
    return this.yourService.getMethod(route.params['id']); 
    } 

在你的OnInit()订阅路由数据与属性someObject