0

I am new to the Angular (so this might be silly doubt) I am building a service where I could call the function from any component and use the service function to provide me the json value in form of object. So i am calling the function from my component and then trying to print my value on console

This is the app-component.ts file

import { Component } from '@angular/core';
import { CallServiceService } from './call-service.service';
import { HttpClient } from '@angular/common/http';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss']
})
export class AppComponent {
  title = 'app';
  message: string;
  obj;

  constructor(private callservice: CallServiceService, private http: HttpClient) {
    console.log("Here in component");
  }

  ngOnInit(): void {
    this.callservice.calledService(this.obj, '/assesment/GetHeaderDetails');
    console.log(this.obj);
  }
}

and my service file is call-service.service.ts

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import 'rxjs/add/operator/catch';
import 'rxjs/add/operator/map';
@Injectable({
  providedIn: 'root'
})
export class CallServiceService {
  base_api_url: string = "http://localhost:5000/";
  process: string = "";
  constructor(private http: HttpClient) {
  }

  calledService(end_url: string) {
    return this.http
      .get(this.base_api_url + end_url)
      .catch(this.handleError)
      .subscribe(data => obj.successCallback(data));
  }

  private handleError(error: any): Promise<any> {
    console.error('An error occurred', error);
    return Promise.reject(error.message || error);
  }
}

So i need to read the value in component file but that is not showing the desired output

1
  • You should subscribe in the service, not in the component Commented Jul 19, 2018 at 14:42

1 Answer 1

1

subscribe calledService in the component.

SERVICE

calledService(end_url: string) {
    return this.http.get(this.base_api_url + end_url);
    // remove subscriber
}

COMPONENT

ngOnInit(): void {
    this.callservice.calledService(this.obj, '/assesment/GetHeaderDetails')
        .subscribe(data => console.log(data));
    // Assign data to some variable and use in HTML
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.