2017-04-20 4 views
4

에서 응용 프로그램 구성 요소로 경로 데이터를 가져 오기 위해 나는 아래처럼 내 응용 프로그램 라우팅 모듈에서 어떤 경로 데이터를 정의하는 방법 :각도 2

나는 내가 app.component을 사용하고 전 세계적으로 데이터를 얻으려면
const appRoutes:Routes = [ 
    {path: '', component: LoginComponent, data:[{PageName:"Login Page"}]}] 

. TS는 아래의 URL 리디렉션 관련 정보를 얻을 수 있습니다 :

export class AppComponent { 
    title = 'Welcome'; 
    constructor(public router: Router, public authenticationService: AuthenticationService) { 
    this.router.events.subscribe(event => { 
     console.log("Url",event.urlAfterRedirects); 
     console.log("Page Name", router[PageName]); //Not working 
     } 

나는 ActivatedRoute를 주입 시도했지만 각 리디렉션 후 업데이트 점점 아니에요.

어쨌든 페이지 이름을 구성하고 글로벌 app.component.ts에서 가져올 수있는 곳이 있습니까? 대신 subscribe

constructor(router:Router, route:ActivatedRoute) { 
    router.events 
     .filter(e => e instanceof NavigationEnd) 
     .forEach(e => { 
     this.title = route.root.firstChild.snapshot.data['PageName']; 
    }); 
} 

답변

8

시도 filter 및 루프하여 이벤트 다음 작업 데모를 확인하시기 바랍니다 : https://plnkr.co/edit/rBToHRaukDlrSKcLGavh?p=info

+0

위 코드를 app.component.ts에 추가했습니다. 값을 정의되지 않은 것으로 가져옵니다. – user1188867

+0

플 런커를 만들 수 있습니까? 그런 식으로 도와주는 것은 어렵습니다. 내 작업 데모가 작동하는 것을 보았으므로 문제를 해결하기 위해 매우 가까워졌습니다. –

+0

사과를 여러 개 모듈로 작성하여 커다란 프로젝트를 만들었습니다. – user1188867

0
export class AppComponent implements OnInit, OnDestroy{ 
    title = 'Welcome'; 
    private paramsSubscription; 

    constructor(public router: Router, 
       private activatedRoute: ActivatedRoute, 
       public authenticationService: AuthenticationService) {} 


public ngOnInit() { 
    this.paramsSubscription = this.activatedRoute.params 
     .subscribe((params) => { 
     console.log("Page Name", params['PageName']); 
     }   
} 

// Unsubscribe route params to avoid memmory leaks 
public ngOnDestroy() { 
    this.paramsSubscription.unsubscribe(); 
} 
+2

그것의 작동하지 않으며 모든 경로를 위해 불려지고 있지 않다. – user1188867

1

정적으로 사용하여 라우팅 한 경우 라우터 개체 아래 같은 :

{path : '', pathMatch : 'full', 구성 요소 : NameComponen t, 데이터 : {여기서 variableName : 'variableValue'}}, 당신은 당신이 라우터의 정의에서 전달 된 데이터를 복구 할 수 ActivatedRoute 객체를 사용할 수 있습니다

ngOnInit (에

) :

ngOnInit() { 이 .localVariable = this.route.snapshot.data [ 'variableName']; }

Obs : 각도 5를 사용하고 있습니다!