2017-04-02 4 views
-1

Oninitを実装するにはどうすればよいですか?& Ondestroy私は下で試したが、私のために働かなかった。Angular2:2つ以上のメソッドを実装する方法

私は私がメモリの問題を回避するために、OnDestroy使用すると、あなたのコードの構文は正常に見えるのOnInit

import { Component, OnInit, OnDestroy } from '@angular/core'; 
 
import { DetailService } from '../detail.service'; 
 
import { Router, ActivatedRoute } from '@angular/router'; 
 
import { Subscription } from 'rxjs'; 
 

 
@Component({ 
 
    selector: 'app-detail-page', 
 
    templateUrl: './detail-page.component.html', 
 
    styleUrls: ['./detail-page.component.css'], 
 
    providers: [DetailService] 
 
}) 
 
export class DetailPageComponent implements OnInit, OnDestroy { 
 
detailData: any; 
 
id:string; 
 
private subscription: Subscription; 
 
    constructor(private detailService: DetailService, private router: Router, private activatedRoute: ActivatedRoute) { 
 
    this.subscription = this.activatedRoute.queryParams.subscribe(
 
     (param: any) => this.id = param['id'] 
 
    ); 
 
    } 
 

 
    ngOnInit() { 
 
     this.detailService.getDetailData() 
 
    .subscribe(
 
    data => this.detailData = data 
 
); 
 
} 
 

 
ngOnDestroy(){ 
 
    this.subscription.unsubscribe(); 
 
} 
 

 
}

+1

あなたは完全なコードを追加することができますか?方法はどこですか? – echonax

+1

エラーメッセージが表示されますか? – zurfyx

+3

'ngOnInit()'のように 'ngOnDestroy()'を実装するだけです。どうしたの? – echonax

答えて

0

サービスを呼び出す必要があり、そのためにURLからIDを抽出しています。スニペットにDetailServiceを含めましたか?

お知らせ:活性化ルートis not necessaryから退会: The ActivatedRoute and its observables are insulated from the Router itself. The Router destroys a routed component when it is no longer needed and the injected ActivatedRoute dies with it.

更新:それはだとき

  • 使用params:あなたはactivatedRoute.params

    constructor(route: ActivatedRoute) { 
        this.params = route.params.subscribe(
         params => this.id = params['id'] 
        ); 
        } 
    

    アップデート2を使用する場合があります代わりにactivatedRoute.queryParamsの パスの一部(例:)

  • 使用queryParamsそれは、オプションのクエリのparamだとき、例えば:page?id=1

詳細情報はhere

+0

DetailServiceをスニペットに入れますか?私は用語のスニペットを知らないので、これを詳しく教えてください。 – Jay

+0

私はStackOverflowスニペットを意味しています。 問題を把握しましたか?代わりに、あなたは私が得る 'activatedRoute.params' – karser

+0

を使用する場合がありますactivatedRoute.queryParams''の「プロパティ 『のparamsは、』タイプ 『ActivatedRoute』に存在しません。 任意の 」 – Jay

関連する問題