2016-09-28 4 views
1

NVM 0.31.0 : login.component.ts에서각도 2 라우팅 - 라우팅 매개 변수를 얻을 - 타이프 라이터

gotoProfile(id:number):void { 
    let link = ['/profile']; 
    console.log("Routing to /profile/"+id); 
    this.router.navigate(link, id); 
} 

콘솔을 Node.js를 6.6.0

: NPM 3.10.3을

C에서 profile.component.ts

import { Router, ActivatedRoute, Params } from '@angular/router'; 

constructor(private route:ActivatedRoute, 
       private router:Router, 
       private profileService:ProfileService) { 
    } 

ngOnInit():void { 
this.route.params 
     .subscribe(params => { 
      let id = params['id']; 
      console.log("id " + id); 
      this.profileService.getProfileById(id) 
      .subscribe(
       p => this.model = p, 
       err => this.handleError(err), 
       () => console.log("getting profile complete") 
      ); 
    }); 

에서

Routing to /profile/1 

onsole :

app.routing.ts에서
id undefined 

path: 'profile/:id', 
component: ProfileComponent 

내가 다음 브라우저에서 입력하면 : http://localhost:3000/profile/1 콘솔 :

id 1 

그래서 내가 여기에 무엇을 잃었 :)

답변

0

subscribe() 방법은 URL의 변화를 감시하지만 요 ur 로그인 구성 요소를 사용하여 라우터를 직접 탐색 할 수 있습니다.

router docs에서 다음 코드 단편은 그런 식으로 매개 변수를 구문 분석하는 방법을 보여줍니다.

ngOnInit() { 
    this.route.params.forEach((params: Params) => { 
    let id = +params['id']; // (+) converts string 'id' to a number 
    this.service.getHero(id).then(hero => this.hero = hero); 
}); 
} 

그러나, URL의 입력은 직접 직접 URL을 관찰되기 때문에 subscribe() 방법을 트리거하고, 그런 식으로 작동을하고있는 이유를 설명하고, 콘솔 로그에 표시됩니다.

+0

이 예제에서는 Observable을 사용하고있는 Promise를 사용하고 있습니다. 나는 새로운 각도이고 나는 영웅 튜토리얼을 통과했다. – klind