I've been using the Heroes tutorial in the Angular 2 docs to experiment. However, I've come to a point that I don't understand what's happening with this error:
Uncaught (in promise): TypeError: Cannot read property 'query' of null
in browser_adapter.ts:88
.
The two pieces involved are the HeroDetailComponent
and the HeroService
.
import { Component, OnInit } from '@angular/core';
import { RouteParams } from '@angular/router-deprecated';
import { Hero, HeroService } from '../index';
@Component({
selector: 'my-hero-detail',
templateUrl: ...
styleUrls: [...]
})
export class HeroDetailComponent implements OnInit {
hero: Hero;
// TEMPORARY FIX:
_heroService = new HeroService(); // Avoids injection
// constructor(private _heroService: HeroService,
// private _routeParams: RouteParams) {}
constructor(private _routeParams: RouteParams) {}
ngOnInit() {
let id = +this._routeParams.get('id');
console.log(id);
}
}
When the I use this code, it works. But when I switch the constructors, and use the one with the HeroService
injection, then I get the error I mentioned earlier.
@Injectable()
export class HeroService {
getHeroes() {
return HEROES;
}
getHero(id: number) {
return new Hero(1, 'Name', 'Power', 'AlterEgo');
}
}
While I was trying to figure out what's going on I removed all the promise-related code. However, I still get the same error. Everything is compiling fine, it's a runtime error. The HeroService
and RouteParams
are provided in a parent component.
Two questions:
- How to solve this issue?
- How to debug this kind of problems?
I'm inclined to think it's a bug in Angular 2, but I'm not sure how make sure that it's not an error on my part. Thanks in advance.
UPDATES:
I've added the the temporary fix code (which avoids injection and thus is not a solution to this question as I would like to have injection working properly).
This is a Plunker with an approximate version of the code I'm trying. I couldn't get it to run properly, but it may be helpful to diagnose the problem by looking into the code.
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…