Angular2:如何实现2个以上的方法

时间:2017-04-02 16:50:38

标签: angular

我如何实施Oninit&的onDestroy。我在下面尝试但是没有为我工作。

我正在从URL中提取id,因为我想使用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 个答案:

答案 0 :(得分:0)

您的代码语法看起来很好。您是否将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.

更新: 您可能希望使用activatedRoute.queryParams

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

UPDATE2:

  • params成为路径的一部分时使用{path: 'page/:id'},例如queryParams
  • page?id=1为可选查询参数时使用from urllib.parse import urlparse def getparts(url): return (url.scheme, url.hostname, url.port) line = "https://dbwebb.se/kunskap/uml#sequence, ftp://bth.com:32/files/im.jpeg,\file://localhost:8585/zipit, http://v2-dbwebb.se/do%hack" urls = [getparts(urlparse(url)) for url in line.split(',')] ,例如:class Device { public bool IsDisabled {get; set;} ...(other properties) }

更多信息是here