Ankur Mukherjee
Ankur Mukherjee

Reputation: 3867

Angular2 function call throws typeerror

I have a function in my service, corresponding to this code:

    @Injectable()
    export class MyService {
constructor(private http: Http, private router: Router) {}
        getInfo() {
            return this.http.get(url).map((response: Response) => {return JSON.parse(response)}
        }
    }

This method is getting called from ngOnInit of a component as mentioned below:

export class MyComponent implements OnInit {
    constructor(private service: MyService) { }

    ngOnInit() {
        this.service.getInfo().subscribe((data) => {
                    this.info = data;
                });
    }
}

The issue is when I am navigating to this component, by putting the url on browser, it works fine, but when I navigate to this component, using router.navigate method, it throws an exception,

getInfo is not a function

Please correct me where is the problem and what am I doing wrong?

Upvotes: 0

Views: 59

Answers (1)

Jaroslaw K.
Jaroslaw K.

Reputation: 5374

You should inject your service to component, where do you use it. You can do that, declararing service as a parameter of your component's constructor. For example:

simple.service.ts

@Injectable()
export class SimpleService {
    constructor(private http: Http) {}
    someMethod() { //some method }
}

some.component.ts

export class SomeComponent implements OnInit {
    constructor(private simpleService: SimpleService) { }

    ngOnInit() {
        this.simpleService.someMethod();
    }
}

I'm not sure, if this a solution but ")" character is missing in your service's method. It should look like that:

return this.http.get(url).map((response: Response) => {return JSON.parse(response)})

or even:

return this.http.get(url).map((response: Response) => response.json())

Upvotes: 2

Related Questions