0

I've just installed a fresh install of Angular 2. But when I try to inject a service called TestService into a login component like this:

LoginComponent:

import {Component, Inject} from '@angular/core';

@Component({
  selector: 'app-login',
  template: `
      {{ test.test }}
  `,
  styles: []
})
export class LoginComponent {
  constructor(@Inject('test') private test){};
}

App

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { HttpModule } from '@angular/http';
import { AppComponent } from './app.component';
import { LoginComponent } from './login/login.component';
import {TestService} from "./test.service";

@NgModule({
  declarations: [
    AppComponent,
    LoginComponent
  ],
  imports: [
    BrowserModule,
    FormsModule,
    HttpModule
  ],
  providers: [{provide: 'test', useClass:TestService}],
  bootstrap: [AppComponent]
})
export class AppModule { }

TestService

import { Injectable } from '@angular/core';

@Injectable()
export class TestService {
  test = 'test';
  constructor() { }
}

I receive an error:

error_handler.js:47EXCEPTION: Error in ./AppComponent class AppComponent - inline template:1:25 caused by: Cannot read property 'name' of undefined

What am I doing wrong?

2
  • The error message doesn't seem to be related to the code in your question. Where and how do you use name in AppComponent? Commented Nov 21, 2016 at 12:23
  • Thanks had a mistake in AppComponent like you said. Commented Nov 21, 2016 at 12:30

1 Answer 1

3

On view you should be using Elvis Operator. Just to make sure test property will ask on test. Currently when initial change detection occurs test.test tries to evaluate binding on view. Since initially test is undefined test.test fails.

{{ test?.test }}
Sign up to request clarification or add additional context in comments.

3 Comments

AFAIK strings as provider keys are fine. Usually using OpaqueToken is a good idea but not mandatory.
@GünterZöchbauer thanks for your headsup, I was totally on wrong track, I can surely say that now. Its related to binding evaluation..
Sounds likely but I'm still missing information in the question where name is accessed that causes Cannot read property 'name'. If your suggestion is correct it would need to be Cannot read property 'test', but I assume it's just inaccuracy in the code provided in the question.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.