注意:我发现文章在实现过程中在 typescript 中找不到 OnInit但下面的代码已经在导入OnInit
/ OnDestroy
。
我发现的所有示例(例如,使用路由参数)都表明在类定义中添加implements OnInit
/子句,并在订阅以从路由获取参数时包括/方法——代码正在这样做。OnDestroy
ngOnInit
ngOnDestroy
但是VS2017子句报错“错误实现OnInit/OnDestroy”,函数报错“Cannot find ngOnInit/ngOnDestroy”。
如果我删除implements
子句并注释ngOnInit
/ngOnDestroy
函数(仅在 的主体中留下代码ngOnInit
),则代码有效;它成功地从路由参数中获取参数。
import { Component, Inject, OnInit, OnDestroy } from '@angular/core';
import { Http } from '@angular/http';
import { ActivatedRoute } from '@angular/router';
@Component({
selector: 'submission',
templateUrl: './submission.component.html'
})
export class SubmissionComponent implements OnInit, OnDestroy {
private baseUrl: string;
private http: Http;
private route: ActivatedRoute;
private sub: any;
public caseId: string;
public submission: Submission;
constructor(http: Http, route: ActivatedRoute, @Inject('BASE_URL') baseUrl: string) {
this.http = http;
this.route = route;
this.baseUrl = baseUrl;
ngOnInit() {
this.sub = this.route.params.subscribe(params => {
this.caseId = params['caseId'];
// In a real app: dispatch action to load the details here.
});
}
ngOnDestroy() {
this.sub.unsubscribe();
}
this.get(this.caseId);
}
public get(caseId: string) {
var url = this.baseUrl + 'api/Submission/GetSubmission?caseId=' + caseId;
this.http.get(url).subscribe(result => {
this.submission = result.json() as Submission;
}, error => console.error(error));
}
public put() {
var url = this.baseUrl + 'api/Submission/PutSubmission';
this.http.put(url, this.submission).subscribe(result => {
this.submission = result.json() as Submission;
}, error => console.error(error));
}
}