2016-12-25 7 views
2

샘플 Angular 2 응용 프로그램에서 작업 중이며 아래에 내 구성 요소 중 하나의 코드가 나와 있습니다.각도 2의 경로 매개 변수

export class ProductComponent implements OnInit { 

    product:Product; 

    constructor(private appService: AppService , private router:Router ,private route:ActivatedRoute) {} 

ngOnInit() 
{ 

    let id:string; 
    let pid:string; 

    this.route.params.subscribe((params) => { 
    id = params['id']; 
    pid = params['pid'];  
    this.appService.GetProduct(id,pid).subscribe(data => { 
     this.product = data; 
    }); 
}) 

}이 partcular 구성 요소에서

, 내 의도는 두 경로 매개 변수 (ID, PID)를 읽고 다음 서비스 메서드를 호출하는 것입니다. 그러나 읽을 경로 매개 변수가 2 개이므로 서비스 메서드가 두 번 호출됩니다.

서비스 메소드를 한 번 호출하도록 수정해야 할 사항은 무엇입니까?

+0

두 개의 라우트 매개 변수가 있기 때문에'this.appService.GetProduct()'가 두 번 호출된다고 말하는가? – inspired

답변

0

을 텍스트 아래 this 링크에서 내 문제를 해결했다.

지금은 구성 요소의 내용 /보기 하위 항목의 변경을 감지하는 동안 오류가 발생하면 ngOnInit가 두 번 호출됩니다 (DynamicChangeDetector 참조). 이로 인해 원래 오류를 숨기는 후속 오류가 발생할 수 있습니다.

내 경우에는 내 구성 요소에 다른 오류가있어서 ngOnInit()가 두 번 실행되었습니다. 다른 사용자에게 도움이되기를 바랍니다. 나는이 이슈에 2 시간을 보냈다. (

0

당신은 switchMap를 사용할 수 있습니다

this.route.params 
.switchMap(({id, pid}) => appService.GetProduct(id,pid)) 
.subscribe(data => this.product = data);