angular 7 service stock HttpClient on varibale in component ts

angular 7 http post example
angular 7 http get example
angular 7 rest api example
httpclient angular 8
angular 6 rest api example
angular httpclient get response headers
angular 8 http post example
angular 2 http get example

In result i get undefined ?? I use contact Api , in service is get data on component html but when i console the result i get undefined.

  element: any ;
  constructor(private service: BlockService) { }
   ngOnInit() {
        this.service.getSource().subscribe(async data=> {
        return  this.element  = await data
    console.log(this.element )

You may can use

  element: any;
  constructor(private service: BlockService) { }
  async ngOnInit() {
    this.element = await this.service.getSource().toPromise();

angular 7 service stock HttpClient on varibale in - html, angular 7 service stock HttpClient on varibale in component ts - angular. Angular 2 - undefinded when sharing variable with API data between component. Teams. Q&A for Work. Stack Overflow for Teams is a private, secure spot for you and your coworkers to find and share information.

Try this

  element: any ;
  constructor(private service: BlockService) { }
   ngOnInit() {
        this.service.getSource().subscribe(data=> {
        this.element  = data;
   //here you can use this.element data

Angular HttpClient v9/8 — Building a Service for Sending API Calls , In this tutorial, you'll be learning, by example, how to use Angular 7/8 and HttpClient to send HTTP requests to remote servers for fetching, This service will be then injected in any component that needs to do any HTTP operations. This will generate the api.service.spec.ts file that contains tests and the� src/app/hero-list.component.ts (constructor) content_copy constructor (private service: HeroService) {}. When Angular discovers that a component depends on a service, it first checks if the injector has any existing instances of that service.

I don't think you need the async and the await key words. The service is async by default

  element: any;
  constructor(private service: BlockService) {}
  ngOnInit() {
    this.service.getSource().subscribe(data => {
      console.log(data); // will log the data
      this.element = data;
    console.log(this.element) // will log null/undefined.


Think of the subscription happening a tick later in the run time. If we have a timeline represented by numbers, the execution of code will happen more or less like this:

  1. construtor code
  2. ngOnInit code
  3. Starting subscription (waiting for response)
  4. console.log('this.element').
  5. Got the response from the subscription, so we get the data, and this.element is set.

Angular 8/7 Tutorial By Example: (REST API, HttpClient GET , In this Angular 8/7 tutorial, you'll learn by example how to send GET how to use the basic concepts of Angular 8 like components and services Next, open the src/app/api.service.ts file and inject HttpClient via the service constructor: Next, define an API_KEY variable which will hold your API key from� In the service class, we will create a function which will display today’s date. We can use the same function in the main parent component app.component.ts and also in the new component new-cmp.component.ts that we created in the previous chapter. Let us now see how the function looks in the service and how to use it in components.

This is not how Observer pattern works you have to subscribe to observer data stream to fetch data. and you cannot grab data without subscribing it!

So there is no use of async or await operator inside of subscription!

in this scenario you can have variable outside of block scope and assign the value after subscribing the observer

export class MyComponent {

  dataToPopulate: any = null;

  constructor(private service: BlockService) {}

  ngOnInit() {
      data => dataToPopulate = {}, // for response 200 OK

      error => console.log(error), // handle network error here {400 or 500 etc}

      () => console.log(this.dataToPopulate) // complete callback hook


Pro tip: Unsubscribe the subscription on component destroy hook to avoid any memory leak

There is another way to convert Observable to Promise toPromise and use async and await operator. But for network calls you need try catch blocks around these statements to detect service error responses like 400 or 500

Communicating with backend services using HTTP, The HTTP client service offers the following major features. app/config/config. service.ts (RxJS imports) app/config/config.component.ts (showConfig v.1) HTTP parameters directly from a query string by using the fromString variable:. A comprehensive tutorial of the Angular HttpClient (version 6/7/8/9/10) that use for consuming RESTAPI service from the remote server. Angular HttpClient is one of the fundamentals features of the Angular 6/7/8/9/10.

Services - ts - TUTORIAL, Routing � 7. Reactive Forms � HTTP Client � Lifecycle Hooks � NgModules � Npm Packages � Pipes � Routing Cut the HEROES array from app.component.ts and paste it to a new file in the app folder What if the service caches heroes and shares that cache with others? The service is in a heroService private variable. Setup Angular HttpClient. Angular 9 HttpClient module already included when creating a new Angular app. We just need to register it this Angular app. Open and edit `src/app/app.module.ts` then add this import of HttpClientModule that is part of @angular/common/http. Before you can use a HttpClient, you need to import an Angular HttpClientModule.

Try it: Manage data, Template reference variables Services are the place where you share data between parts of your application. Open app.module.ts and add a route for the component CartComponent , with a path of cart : The Angular HTTP client, HttpClient , is a built-in way to fetch data from external APIs and provide them to your� The HeroService could get Hero data from anywhere—a web service, local storage, or a mock data source. Removing data access from the component means you can change your mind about the implementation anytime, without touching the components that need hero data.

Add services, Built-in directives � Template reference variables Services are a great way to share information among classes that don't know each other. You'll create a src /app/heroes/heroes.component.ts (import HeroService) In a later tutorial on HTTP, you'll learn that Angular's HttpClient methods return RxJS Observable s. In this� src/app/hero.service.ts content_copy getHeroes (): Hero [] {return HEROES;} Provide the HeroServicelink. You must make the HeroService available to the dependency injection system before Angular can inject it into the HeroesComponent by registering a provider.

  • You log the data before you await it.
  • remove async and await. And whatever you want to do after data fetched, do it inside subscribe block.
  • even after i remove steel undefined
  • @HardikPatel => did mean there is no way to get data outside the subscribe
  • I first need to understand your case why you require data outside subscribe function.
  • yuh i have erreur core.js:15723 ERROR Error: Uncaught (in promise): TypeError: this.service.getSource(...).toPromise is not a function
  • I have edited the code check once whether this is what you required
  • yes i understand the code but in my case is so difficult to use it like that
  • can you add it in that i can help you
  • yes there is any explanation why data get null even we know that service is async !!?
  • It will be null/undefined because the code inside the subscription will be run one tick after the rest of the code, so this.element is not initialized yet.