Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Function declared in service gets "is not a function"

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

like image 810
Ivan Bespalov Avatar asked Nov 29 '25 16:11

Ivan Bespalov


1 Answers

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){
like image 125
snorkpete Avatar answered Dec 02 '25 06:12

snorkpete



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!