Angular 2 - Cannot read property 'get' of undefined (http undefined)

后端 未结 2 601
天命终不由人
天命终不由人 2021-01-17 12:35

Novice to Angular2 and running into strange issue. When rendering index.html the app.component renders the html part OK, but it fails on data call in user.service.t

相关标签:
2条回答
  • 2021-01-17 13:09

    In your app.module.ts, import UserService like this-

    import { UserService } from './services/user.service';
    

    Provide it in NgModule like this-

    @NgModule({
        imports: [BrowserModule,HttpModule],
        declarations: [ AppComponent ],
        providers: [ UserService ],
        bootstrap:    [ AppComponent ]
    })
    

    See if this helps.

    0 讨论(0)
  • 2021-01-17 13:17

    You need to provide the user service in your app.module and remove the @Inject and the providers entry in the app.component:

    app.module.ts

    import { NgModule } from '@angular/core';
    import { HttpModule } from '@angular/http';
    import { BrowserModule } from '@angular/platform-browser';
    import { AppComponent }   from './app.component';
    //Add your UserService import here
    
    @NgModule({
        imports: [
            BrowserModule,
            HttpModule],
      declarations: [ AppComponent ],
      bootstrap:    [ AppComponent ],
      providers:    [ UserService ]
    })
    export class AppModule { }
    

    app.component.ts

    import { Component, OnInit, Inject } from '@angular/core';
    import { UserService } from './services/user.service';
    import { User } from './models/user';
    
    @Component({
        selector: 'my-app',
        templateUrl: 'app/app.component.html'
    })
    export class AppComponent implements OnInit {
        user: User;
    
        constructor(
            private _userService: UserService) {
        }
        getCurrentUser() {
            this._userService.getCurrentUser()
                .subscribe(user => this.user = user);
        }
        ngOnInit() {
            this.getCurrentUser();
        }
    }
    

    this way, UserService dependencies are managed by the injector and you don't provide the service directly to your component (this behaviour is deprecated or even removed, don't know since final release).

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