Reputation: 147
This is a service, for testing it simply returns an array of 1,2,3
import {Injectable} from '@angular/core';
@Injectable()
export class CitiesService {
getCities() {
return ['1', '2', '3'];
}
}
AppComponent is a autocomplete box. Formbuilder is used to reference the input field and get the value user types in.
The goal of using CitiesService is to get a list of cities from json file.
import { Component, Inject } from '@angular/core';
import { Observable } from 'rxjs/RX';
import { FormBuilder, FormGroup, FormsModule } from '@angular/forms';
import { CitiesService } from './cities.service';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css'],
providers: [CitiesService]
})
export class AppComponent {
form: FormGroup;
searchTerm: string;
constructor(@Inject(FormBuilder) private _CitiesService: CitiesService, private _fb: FormBuilder){
var a = this._CitiesService.getCities();
this.form = _fb.group({
search: []
});
var search = this.form.controls['search'];
search.valueChanges
.subscribe(data => this.searchTerm = data);
}
}
But I get this error
EXCEPTION: this._CitiesService.getCities is not a function
Upvotes: 3
Views: 4504
Reputation: 14564
You're trying to inject your _CitiesService as a FormBuilder
constructor(@Inject(FormBuilder) private _CitiesService: CitiesService, private _fb: FormBuilder){
That line says that your first parameter to your constructor, _CitiesService
, should be injected by using the provider for FormBuilder (@Inject(FormBuilder)
). I sincerely doubt this is what you meant to do.
Instead, remove that @Inject(FormBuilder) - first off, it's not needed unless the type of your constructor parameter doesn't match the type that is used to register as a provider. Secondly, even if you really wanted to use it, you have to put the @Inject in front of the parameter to which it applies.
So, change your line to:
constructor(private _CitiesService: CitiesService, @Inject(FormBuilder) private _fb: FormBuilder){
Or preferably,
constructor(private _CitiesService: CitiesService, private _fb: FormBuilder){
Upvotes: 2