Teo96
Teo96

Reputation: 11

Angular subscribe() returning undefined

How to I solve problem with subcribe() to my app.component if my console shows me the following thing: ERROR TypeError: Cannot read property 'subscribe' of undefined at AppComponent.push../src/app/app.component.ts.AppComponent.ngOnInit

data.service:

   import { Injectable } from '@angular/core';
   import { Http, Response } from '@angular/http';

   import { Injectable } from '@angular/core';
   import { Observable, Subject, ReplaySubject } from 'rxjs';
   import { from, of, range } from 'rxjs/create';
   import { map, filter, switchMap } from 'rxjs/operators';


 @Injectable({
    providedIn: 'root'
    })


export class DataService {

  constructor(private http: Http) { }

  fetchData(){
    this.http.get('assets/ninjas.json').pipe(
     map((res) => return res.json()))}}

app.components:

import { Component } from '@angular/core';
import { DataService } from './data.service';

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

export class AppComponent {
  title = 'app';
  ninjas = [];

  constructor(private newService: DataService){ }

  ngOnInit(){
   this.newService.fetchData().subscribe(
    (data) => this.ninjas = data;
   );
  }
 }

Upvotes: 0

Views: 2871

Answers (2)

Eddie Paz
Eddie Paz

Reputation: 2241

Simply remove the 'pipe', you don't need it:

fetchData(){
    return this.http.get('assets/ninjas.json');
}

Upvotes: 0

Sajeetharan
Sajeetharan

Reputation: 222552

Return the observable in your service,

 fetchData(){
    return this.http.get('assets/ninjas.json').pipe(
     map((res) => return res.json()))}}

Upvotes: 1

Related Questions