Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to fix Angular 2 `Uncaught (in promise): TypeError: Cannot read property 'query' of null`?

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:

  1. How to solve this issue?
  2. 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:

  1. 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).

  2. 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.

like image 246
Omar Trejo Avatar asked May 08 '16 22:05

Omar Trejo


1 Answers

I see the following problem: HeroComponent depends on HeroDetailsComponent, but HeroDetailsComponent is exported afterwards in the app/heroes/index.ts file.

Someone reported a problem with this kind of set up here

like image 180
Martín Coll Avatar answered Oct 12 '22 07:10

Martín Coll