2016-09-27 21 views
4

我想在另一個服務中使用ActivatedRoute服務。但是,在我的服務中,ActivatedRoute服務正在監視主應用程序組件,並且沒有任何路由參數變化正在從observable發出。如果我在同一個模塊的組件中觀察路由參數,則ActivatedRoute服務按預期運行。在另一個服務中使用ActivatedRoute

這裏是我的目錄的簡化版本,它

app/ 
├──app.module.ts   <- RouterModule Imported Here 
├──app.component.ts 
| 
└──other-module/ 
    ├──other.module.ts  <- other.service provided here 
    ├──other.component.ts <- ActivatedRoute works as expected 
    └──other.service.ts <- ActivatedRoute watches App component 

這裏是我的路線配置的簡化版本:

export const routes: Routes = [ 
    { path: '', component: App }, 
    { path: 'other/:id', component: Other } 
]; 

誰能提供了一些與如何正確處理和注入服務,以便我可以使用另一項服務中的ActivatedRoute服務。

謝謝。

+0

我有同樣的問題 – piernik

回答

0

我遇到了類似的問題,找不到合適的解決方案。事實上,我剛剛打開了一個錯誤報告(見https://github.com/angular/angular/issues/12938),要麼檢查它,要麼就我們應該如何解決這個問題得到一些指導。

作爲一個臨時的解決辦法然而,我還是設法使用下面的

this.router.navigate([ this.router.url.concat('/relativepath') ]); 

注意,這是一個真正實現了導航相對於當前的URL從服務(不記層次更深)真的哈克暫時的解決辦法,應予以更換,以適當的

this.router.navigate(['./relativepath'], {relativeTo: this.activatedRoute}) 

應此功能成爲支撐。

1

在角2.1.0,我有ActivatedRoute的這個簡單的用法工作(注意,我使用queryParams代替params因爲我想匹配類似?name=Joe。參考https://stackoverflow.com/a/39146396/4185989用於對更多的信息。)

編輯:這有可能是我下面的解決方案是唯一的,因爲我找queryParams,而不是像:id組件URL的片段 - 我看到有在https://github.com/angular/angular/issues/11023申請後者的角度問題。儘管如此,留下我的答案,對於那些可能像我一樣想要queryParams的人來說。

user.service.ts
import {Injectable} from "@angular/core"; 
import {ActivatedRoute} from "@angular/router"; 

import {Subscription} from "rxjs/Rx"; 
import {UserModel} from "./shared/user.model"; 

@Injectable() 
export class UserService { 
    protected user: UserModel; 
    protected subscription: Subscription; 

    constructor(protected activatedRoute: ActivatedRoute) { 
    this.subscription = this.activatedRoute.queryParams.subscribe(
     (queryParams: any) => { 
     if (queryParams.name) { 
      this.setUser(queryParams.name); 
     } 
     } 
    ) 
    } 

    setUser(name) { 
    this.user = new UserModel(name); 
    console.log('Setting user', this.user); 
    } 

} 

user.model.ts
import {Injectable} from "@angular/core"; 

@Injectable() 
export class UserModel { 

    constructor(public name: string) {} 
} 

user.module.ts
import { NgModule } from '@angular/core'; 
import {UserService} from "./user.service"; 

@NgModule({ 
    imports: [ 
    ], 
    declarations: [ 
    ], 
    exports: [ 
    ], 
    providers: [ 
    UserService 
    ] 
}) 
export class UserModule { } 

app.component.ts
import { Component } from '@angular/core'; 
import {UserService} from "./core/user/user.service"; 

@Component({ 
    selector: 'app-root', 
    templateUrl: './app.component.html', 
    styleUrls: ['./app.component.css'] 
}) 
export class AppComponent { 

    constructor(
    protected userService: UserService 
) { 
    } 
} 
相關問題