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

前端 未结 6 1284
甜味超标
甜味超标 2020-12-10 03:36

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:

相关标签:
6条回答
  • 2020-12-10 04:10

    Try with these compilerOptions in "tsconfig.json". It worked for me (Version 2.0.0-rc.1 of angular).

    "compilerOptions": {
        "target": "es6",
        "module": "commonjs",
        "declaration": false,
        "noImplicitAny": false,
        "removeComments": true,
        "noLib": false,
        "emitDecoratorMetadata": true,
        "experimentalDecorators": true   },
    

    I had the same problem with injectables (same error) and the fix did the trick for services but not for http. I modified my options based on a tutorial from ng-book2 and it finally worked.

    0 讨论(0)
  • 2020-12-10 04:15

    I got this error with angular RC1 when I was injecting FormBuilder inside the constructor like this:

    export class App {
      constructor(public formBuilder: FormBuilder) {}
    }
    

    But I didn't import it previously! Just add it solves the problem:

    import { FormBuilder } from '@angular/common'

    0 讨论(0)
  • 2020-12-10 04:17

    The correct answer as of RC1 is to add the @Inject(Service) private service:Service wherever you are injecting services.

    This caused me no end of headache after I upgraded on Monday to RC1.

    0 讨论(0)
  • 2020-12-10 04:28

    In my case, I fix this problem using @Inject decorator. Try this:

    import {Inject} from '@angular/core'
    
    constructor(@Inject(HeroService) private _heroService: HeroService,
                @Inject(RouteParams) private _routeParams: RouteParams) {}
    

    My project is configured with JSPM and this is the only way to work with dependency injection, I do not why, anyone has an explanation?

    Edited: I have found the solution. In my case, I have to add this configuration into config.js file

    System.config({
     baseURL: "",
     defaultJSExtensions: true,
     transpiler: "typescript",
     typescriptOptions: {
        "target": "es5",
        "emitDecoratorMetadata": true
     },
     paths: {
        "npm:*": "jspm_packages/npm/*",
     ....
    

    Now I can remove @Inject decorator and this sentence works properly

    constructor(private _heroService: HeroService,
                private _routeParams: RouteParams) {}
    

    The key is emitDecoratorMetadata: true

    0 讨论(0)
  • 2020-12-10 04:29

    In the "tsconfig.json" set "emitDecoratorMetadata" parameter of the "compilerOptions" section to the "true" value.

    0 讨论(0)
  • 2020-12-10 04:32

    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

    0 讨论(0)
提交回复
热议问题