NOTE: I found the article cannot find OnInit in typescript during implementation but the code below is already importing OnInit
/OnDestroy
.
All the examples I've found (e.g., Using Route Parameters) indicate adding the implements OnInit
/OnDestroy
clause to the class definition and including the ngOnInit
/ngOnDestroy
methods when subscribing to obtain a parameter from the route -- which the code is doing.
However, VS2017 reports the error "incorrectly implements OnInit/OnDestroy" for the clause and reports the error "Cannot find ngOnInit/ngOnDestroy" for the functions.
If I remove the implements
clause and comment the ngOnInit
/ngOnDestroy
functions (leaving only the code in the body of the ngOnInit
), the code works; it successfully obtains the parameter from the route parameters.
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));
}
}
The methods ngOnInit
and ngOnDestroy
should be outside the constructor. Like this:
// imports ...
@Component({
// ...
})
export class SubmissionComponent implements OnInit, OnDestroy {
// ...
constructor( /* ... */ ) {
// ...
}
ngOnInit() {
// ...
}
ngOnDestroy() {
// ...
}
}