Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular2 EXCEPTION No provider for String

I've got a brand new app create with a ng-cli with this very simple code ^^

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

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  constructor(private my: string) {}
} 

and I've got in the console

EXCEPTION: No provider for String!

I don't see any error in the code so what's wrong !

In ng-book I can read

export class Article { 
  title: string; 
  link: string; 
  votes: number;
  constructor(title: string, link: string, votes?: number) { 
    this.title = title;
    this.link = link;
    this.votes = votes || 0;
  }
}

Take a look at

https://github.com/Microsoft/TypeScriptSamples/blob/master/greeter/greeter.ts

like image 929
Whisher Avatar asked Jan 26 '17 20:01

Whisher


1 Answers

Error in constructor:

export class AppComponent {
  constructor(private my: string) {}
} 

private my: string should not be injected in the constructor, but outside, here assuming it's a variable you want to use in your component.

export class AppComponent {
  private my: string;
  constructor() {
    this.my = 'Hello!'; // if you want to assign a value (in the constructor) to your string, do it here!
  }
} 

I suggest you start of with the Tutorial from the beginning, so you learn the basics of Angular :)

EDIT, the latter part you added is a class e.g for typing your object, not a component, for a typed Object of class Article, this is valid syntax:

export class Article { 
  title: string; 
  link: string; 
  votes: number;
  constructor(title: string, link: string, votes?: number) { 
    this.title = title;
    this.link = link;
    this.votes = votes || 0;
  }
}

Then you can import this class to your AppComponent, and use to assign an Article object.

import { Component } from '@angular/core';
import { Article } from './your.path'

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {

  article: Article = new Article('titleHere', 'linkHere', 3)

  constructor() {}
}
like image 142
AT82 Avatar answered Sep 25 '22 02:09

AT82