How to Implement Map API in Angular 8

How to Implement Map API in Angular 8

In this article, we will learn how to implement Here Map API with Angular 8. We're gonna use it in combination with the Here Map API integration for Angular.

In this post, we will discuss how to implement Here Map API with Angular 8. On today’s web-based applications, mapping solutions is a natural part of the application. We normally use them to see the location of things, to search for any address, to get the driving directions and also many more different types of actions. Basically, applications and web sites always combine with data. Normally, data or functionality from two or more sources is commonly referred to as mashups.

Nowadays, mashups are becoming much more popular and have revolutionized the way information is being used and visualized. Mapping solutions are one important ingredient in a lot of these mashups. The Here Map API provides us with an easy way to display our own data in an efficient and usable manner.

For using the Here Map API, we first need to generate an API key and API Code from the Here Map Web Sites. For that purpose, we need to perform the below steps,

Step 1

First, open the URL:- https://developer.here.com/products/maps and click on the Sign In link in the top right corner.

Step 2

After successful Sign In, click on the "Get a Free API Key" button.

Step 3

Now, click on the "Generate API Key" button. It will generate the API ID and APP Code for accessing the Here Map API. Copy these codes which we need to use in the Angular Components.

Step 4

Now, create a new Angular CLI Project using ng new command.

Step 5

Now open the above Angular cli project in Visual Studio Code Editor. Now open the Index.html file and use the below file reference in the index page for using the Here Map API.

<!doctype html>  
<html lang="en">  
<head>  
  <meta charset="utf-8">  
  <title>HereMapDemo</title>  
  <base href="/">  
  
  <meta name="viewport" content="width=device-width, initial-scale=1">  
  <link rel="icon" type="image/x-icon" href="favicon.ico">  
  <link rel="stylesheet" type="text/css" href="https://js.api.here.com/v3/3.0/mapsjs-ui.css?dp-version=1533195059" />  
</head>  
<body>  
  <app-root></app-root>  
  <script src="https://js.api.here.com/v3/3.0/mapsjs-core.js" type="text/javascript" charset="utf-8"></script>  
  <script src="https://js.api.here.com/v3/3.0/mapsjs-service.js" type="text/javascript" charset="utf-8"></script>  
  <script src="https://js.api.here.com/v3/3.0/mapsjs-places.js" type="text/javascript" charset="utf-8"></script>  
  <script src="https://js.api.here.com/v3/3.0/mapsjs-mapevents.js" type="text/javascript" charset="utf-8"></script>  
  <script src="https://js.api.here.com/v3/3.0/mapsjs-ui.js" type="text/javascript" charset="utf-8"></script>  
</body>  
</html>  

Step 6

Now, open the app.component.html file under app folder and replace the html file code with the below code,

<div #map [style.width]="width" [style.height]="height"></div>  

Step 7

Now, open the app.component.ts file and write down the below code to generate the basic map objects in the browser,

import { Component, OnInit, ViewChild, ElementRef, Input } from '@angular/core';  
import { HttpClient, HttpHeaders } from '@angular/common/http';  
  
declare var H: any;  
  
@Component({  
  selector: 'app-root',  
  templateUrl: './app.component.html',  
  styleUrls: ['./app.component.css']  
})  
export class AppComponent {  
  title = 'HereMapDemo';  
  
  @ViewChild("map", { static: true }) public mapElement: ElementRef;  
  
  public lat: any = '22.5726';  
  public lng: any = '88.3639';  
  
  public width: any = '1000px';  
  public height: any = '600px';  
  
  private platform: any;  
  private map: any;  
  
  private _appId: string = 'xxxxxx';  
  private _appCode: string = 'uuuuuu';  
  
  public constructor() {  
      
  }  
  
  public ngOnInit() {  
    this.platform = new H.service.Platform({  
      "app_id": this._appId,  
      "app_code": this._appCode,  
      useHTTPS: true  
    });  
      
  }  
  
  public ngAfterViewInit() {  
    let pixelRatio = window.devicePixelRatio || 1;  
    let defaultLayers = this.platform.createDefaultLayers({  
      tileSize: pixelRatio === 1 ? 256 : 512,  
      ppi: pixelRatio === 1 ? undefined : 320  
    });  
  
    this.map = new H.Map(this.mapElement.nativeElement,  
      defaultLayers.normal.map, { pixelRatio: pixelRatio });  
  
    var behavior = new H.mapevents.Behavior(new H.mapevents.MapEvents(this.map));  
    var ui = H.ui.UI.createDefault(this.map, defaultLayers);  
  
    this.map.setCenter({ lat: this.lat, lng: this.lng });  
    this.map.setZoom(14);  
  }  
  
}  

Now, run the code and result will be as below,

Create Pointers in the Map Against any Given Address

Now, we want to mark any particular map position against any given address. For that, we first need to add the below code in the app.component.html file as below,

<div style="padding: 10px 0">  
  <input type="text" placeholder="Search places..." [(ngModel)]="query" style="width: 90%;" />  
  <button (click)="places(query)">Search</button>  
</div>  
  
<div #map [style.width]="width" [style.height]="height"></div>  

Now, open the app.component.ts file and change the code as below,

import { Component, OnInit, ViewChild, ElementRef, Input } from '@angular/core';  
import { HttpClient, HttpHeaders } from '@angular/common/http';  
  
declare var H: any;  
  
@Component({  
  selector: 'app-root',  
  templateUrl: './app.component.html',  
  styleUrls: ['./app.component.css']  
})  
export class AppComponent {  
  title = 'HereMapDemo';  
  
  @ViewChild("map", { static: true }) public mapElement: ElementRef;  
  
  public lat: any = '22.5726';  
  public lng: any = '88.3639';  
  
  public width: any = '1000px';  
  public height: any = '600px';  
  
  private platform: any;  
  private map: any;  
  
  private _appId: string = 'xxxxx';  
  private _appCode: string = 'xxxx';  
  
  public query: string;  
  private search: any;  
  private ui: any;  
  
  
  public constructor() {  
    this.query = "";  
  }  
  
  public ngOnInit() {  
    this.platform = new H.service.Platform({  
      "app_id": this._appId,  
      "app_code": this._appCode,  
      useHTTPS: true  
    });  
    this.search = new H.places.Search(this.platform.getPlacesService());  
  }  
  
  public ngAfterViewInit() {  
    let pixelRatio = window.devicePixelRatio || 1;  
    let defaultLayers = this.platform.createDefaultLayers({  
      tileSize: pixelRatio === 1 ? 256 : 512,  
      ppi: pixelRatio === 1 ? undefined : 320  
    });  
  
    this.map = new H.Map(this.mapElement.nativeElement,  
      defaultLayers.normal.map, { pixelRatio: pixelRatio });  
  
    var behavior = new H.mapevents.Behavior(new H.mapevents.MapEvents(this.map));  
    var ui = H.ui.UI.createDefault(this.map, defaultLayers);  
  
    this.map.setCenter({ lat: this.lat, lng: this.lng });  
    this.map.setZoom(14);  
  
      
  }  
  
  public places(query: string) {  
    this.map.removeObjects(this.map.getObjects());  
    this.search.request({ "q": query, "at": this.lat + "," + this.lng }, {}, data => {  
      for (let i = 0; i < data.results.items.length; i++) {  
        this.dropMarker({ "lat": data.results.items[i].position[0], "lng": data.results.items[i].position[1] }, data.results.items[i]);  
        if (i == 0)  
          this.map.setCenter({ lat: data.results.items[i].position[0], lng: data.results.items[i].position[1] })  
      }  
    }, error => {  
      console.error(error);  
    });  
  }  
  
  private dropMarker(coordinates: any, data: any) {  
    let marker = new H.map.Marker(coordinates);  
    marker.setData("<p>" + data.title + "<br>" + data.vicinity + "</p>");  
    marker.addEventListener('tap', event => {  
      let bubble = new H.ui.InfoBubble(event.target.getPosition(), {  
        content: event.target.getData()  
      });  
      this.ui.addBubble(bubble);  
    }, false);  
    this.map.addObject(marker);  
  }  
  
}  

The output of the above code is as below,

Fetch Geo Code along with Address on Mouse Click in any position of the Map

Now, to retrieve and display the Geo Code along with address, we need to add the below HTML code in the app.component.html file.

<div style="padding: 10px 0">  
  <input type="text" placeholder="Search places..." [(ngModel)]="query" style="width: 90%;" />  
  <button (click)="places(query)">Search</button>  
</div>  
  
<div #map [style.width]="width" [style.height]="height"></div>  
  
<div style="padding: 10px 0">  
  <div class="col-xxl-12">  
    <div class="red-800">  
      <label>Latitude : {{lat}}</label>  
          
      <label>Longitude : {{lng}}</label>  
    </div>  
    <div class="blue-800">  
      <label>Address : {{address}}</label>  
    </div>  
  </div>  
</div>  

Add the below marked code in the app.compoent.ts file to fetch the geo code and address.

import { Component, OnInit, ViewChild, ElementRef, Input } from '@angular/core';  
import { HttpClient, HttpHeaders } from '@angular/common/http';  
  
declare var H: any;  
  
@Component({  
  selector: 'app-root',  
  templateUrl: './app.component.html',  
  styleUrls: ['./app.component.css']  
})  
export class AppComponent {  
  title = 'HereMapDemo';  
  
  @ViewChild("map", { static: true }) public mapElement: ElementRef;  
  
  public lat: any = '22.5726';  
  public lng: any = '88.3639';  
  
  public width: any = '1000px';  
  public height: any = '600px';  
  
  private platform: any;  
  private map: any;  
  
  private _appId: string = 'xxxx';  
  private _appCode: string = 'xxxx';  
  
  public query: string;  
  private search: any;  
  private ui: any;  
  public address: string = '';  
  
  public constructor() {  
    this.query = "";  
  }  
  
  public ngOnInit() {  
    this.platform = new H.service.Platform({  
      "app_id": this._appId,  
      "app_code": this._appCode,  
      useHTTPS: true  
    });  
    this.search = new H.places.Search(this.platform.getPlacesService());  
  }  
  
  public ngAfterViewInit() {  
    let pixelRatio = window.devicePixelRatio || 1;  
    let defaultLayers = this.platform.createDefaultLayers({  
      tileSize: pixelRatio === 1 ? 256 : 512,  
      ppi: pixelRatio === 1 ? undefined : 320  
    });  
  
    this.map = new H.Map(this.mapElement.nativeElement,  
      defaultLayers.normal.map, { pixelRatio: pixelRatio });  
  
    var behavior = new H.mapevents.Behavior(new H.mapevents.MapEvents(this.map));  
    var ui = H.ui.UI.createDefault(this.map, defaultLayers);  
  
    this.map.setCenter({ lat: this.lat, lng: this.lng });  
    this.map.setZoom(14);  
  
    this.setUpClickListener(this.map);  
  }  
  
  public places(query: string) {  
    this.map.removeObjects(this.map.getObjects());  
    this.search.request({ "q": query, "at": this.lat + "," + this.lng }, {}, data => {  
      for (let i = 0; i < data.results.items.length; i++) {  
        this.dropMarker({ "lat": data.results.items[i].position[0], "lng": data.results.items[i].position[1] }, data.results.items[i]);  
        if (i == 0)  
          this.map.setCenter({ lat: data.results.items[i].position[0], lng: data.results.items[i].position[1] })  
      }  
    }, error => {  
      console.error(error);  
    });  
  }  
  
  private dropMarker(coordinates: any, data: any) {  
    let marker = new H.map.Marker(coordinates);  
    marker.setData("<p>" + data.title + "<br>" + data.vicinity + "</p>");  
    marker.addEventListener('tap', event => {  
      let bubble = new H.ui.InfoBubble(event.target.getPosition(), {  
        content: event.target.getData()  
      });  
      this.ui.addBubble(bubble);  
    }, false);  
    this.map.addObject(marker);  
  }  
  
  public setUpClickListener(map: any) {  
    let self = this;  
    this.map.addEventListener('tap', function (evt) {  
      let coord = map.screenToGeo(evt.currentPointer.viewportX, evt.currentPointer.viewportY);  
      self.lat = Math.abs(coord.lat.toFixed(4)) + ((coord.lat > 0) ? 'N' : 'S');  
      self.lng = Math.abs(coord.lng.toFixed(4)) + ((coord.lng > 0) ? 'E' : 'W');  
      self.fetchAddress(coord.lat, coord.lng);  
    });  
  }  
  
  private fetchAddress(lat: any, lng: any): void {  
    let self = this;  
    let geocoder: any = this.platform.getGeocodingService(),  
      parameters = {  
        prox: lat + ', ' + lng + ',20',  
        mode: 'retrieveAreas',  
        gen: '9'  
      };  
  
  
    geocoder.reverseGeocode(parameters,  
      function (result) {  
        let data = result.Response.View[0].Result[0].Location.Address;  
        self.address = data.Label + ', ' + data.City + ', Pin - ' + data.PostalCode + ' ' + data.Country;  
      }, function (error) {  
        alert(error);  
      });  
  }  
  
}  

Now, the output will be as below.

Conclusion

Now, in this post, we discussed how to implement Here Map API using Angular 8. I hope this will help the readers to understand how to use Here Map in any application.

Thank you

How to Consume a GraphQL API with Angular

How to Consume a GraphQL API with Angular

In this article, we will show you how to use Angular to Consume a GraphQL API.

To download the source code, visit the Consuming a GraphQL API with Angular Source Code.

For the complete navigation of this tutorial visit GraphQL ASP.NET Core Tutorial.

Preparing the Angular Project

After we have finished with the ASP.NET Core client app, let’s create an Angular app as well.

We are going to start by creating a new Angular project without navigation module and with CSS as default styles. As soon as creation is over, we are going to install a set of libraries required for the Apollo Client to work with Angular:

npm install apollo-angular apollo-angular-link-http apollo-client apollo-cache-inmemory graphql-tag graphql -- save

The next step is to modify app.module.ts file:

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { ApolloModule } from 'apollo-angular';
import { HttpLinkModule } from 'apollo-angular-link-http';
import { HttpClientModule } from '@angular/common/http';
 
import { AppComponent } from './app.component';
 
@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    ApolloModule,
    HttpLinkModule,
    HttpClientModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

We import the ApolloModule and HttpLinkModule files, required for the Appolo integration with Angular. But, we can see that HttpClientModule is included as well. That’s because in order to work properly, HttpLinkModule internally uses HttpClientModule.

Let’s move on.

In the same way that we created model files for the ASP.NET Core client application, we are going to create them here.

So, let’s create a new folder „types“ and inside several type files:

export type OwnerInputType = {
    name: string;
    address: string;
}


export type AccountType = {
    'id': string;
    'description': string;
    'ownerId' : string;
    'type': string;
}


import { AccountType } from './accountType';
 
export type OwnerType = {
    'id': string;
    'name': string;
    'address': string;
    'accounts': AccountType[];
}

Now, we can create a graphql.service.ts file and modify it as well:

import { Injectable } from '@angular/core';
import { Apollo } from 'apollo-angular';
import { HttpLink } from 'apollo-angular-link-http';
import { InMemoryCache } from 'apollo-cache-inmemory';
import gql from 'graphql-tag';
import { OwnerType } from './types/ownerType';
import { OwnerInputType } from './types/ownerInputType';
 
@Injectable({
  providedIn: 'root'
})
export class GraphqlService {
  public owners: OwnerType[];
  public owner: OwnerType;
  public createdOwner: OwnerType;
  public updatedOwner: OwnerType;
 
  constructor(private apollo: Apollo, httpLink: HttpLink) {
    apollo.create({
      link: httpLink.create({ uri: 'https://localhost:5001/graphql' }),
      cache: new InMemoryCache()
    })
  }
}

We have an instance of the Apollo service with all the required configuration (link and cache). Both properties are required and must be populated.

After these configuration actions, we are ready to create some queries.

Creating Queries and Mutations

Let’s modify the graphql.service.ts file, by adding our first query:

public getOwners = () => {
    this.apollo.query({
      query: gql`query getOwners{
      owners{
        id,
        name,
        address,
        accounts{
          id,
          description,
          type
        }
      }
    }`
    }).subscribe(result => {
      this.owners = result.data as OwnerType[];
	console.log(this.owners);
    })
  }

We are using the Apollo service with its query function to write the entire GraphQL query. We’re using the imported gql tag as well, in order to be able to write GraphQL code as a multi-line string.

Now, let’s modify the app.component.ts file in order to test this query:

import { Component, OnInit } from '@angular/core';
import { GraphqlService } from './graphql.service';
 
@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent  implements OnInit{
 
  constructor(private service: GraphqlService) {
  }
 
  ngOnInit(): void {
    this.service.getOwners();
  }
  title = 'angulargraphqlclient';
}

As soon as we start the Angular application, we can inspect the result:

Excellent.

Here are all the other queries and mutations from the graphql.service.ts file:

Get by Id Query
public getOwner = (id) => {
    this.apollo.query({
      query: gql`query getOwner($ownerID: ID!){
      owner(ownerId: $ownerID){
        id,
        name,
        address,
        accounts{
          id,
          description,
          type
        }
      }
    }`,
      variables: { ownerID: id }
    }).subscribe(result => {
      this.owner = result.data as OwnerType;
    })
  }


Create mutation example
public createOwner = (ownerToCreate: OwnerInputType) => {
    this.apollo.mutate({
      mutation: gql`mutation($owner: ownerInput!){
        createOwner(owner: $owner){
          id,
          name,
          address
        }
      }`,
      variables: {owner: ownerToCreate}
    }).subscribe(result => {
      this.createdOwner = result.data as OwnerType;
    })
  }


Update mutation example
public updateOwner = (ownerToUpdate: OwnerInputType, id: string) => {
    this.apollo.mutate({
      mutation: gql`mutation($owner: ownerInput!, $ownerId: ID!){
        updateOwner(owner: $owner, ownerId: $ownerId){
          id,
          name,
          address
        }
      }`,
      variables: {owner: ownerToUpdate, ownerId: id}
    }).subscribe(result => {
      this.updatedOwner = result.data as OwnerType;
    })
  }


Delete mutation example
public deleteOwner = (id: string) => {
    this.apollo.mutate({
      mutation: gql`mutation($ownerId: ID!){
        deleteOwner(ownerId: $ownerId)
       }`,
      variables: { ownerId: id}
    }).subscribe(res => {
      console.log(res.data);
    })
  }

You can test them by modifying the app.component.ts file, or if you want to create a new component to consume all these results.

Conclusion

We have learned a lot of great stuff about GraphQL and its integration with ASP.NET Core. Of course, with these last two articles, we went even further, by creating two client applications to consume our GraphQL app.

We hope you have enjoyed this tutorial and if you have any suggestions or question, don’t hesitate to leave a comment in the comment section. If you liked this post, share it with all of your programming buddies!

Further reading

☞ A Beginner’s Guide to GraphQL

Building a Secure API with GraphQL & Spring Boot

Building A GraphQL API With Nodejs And MongoDB

☞ GraphQL with React: The Complete Developers Guide

☞ How to create a simple CRUD App using GraphQL and Node.js

☞ Node, Express, PostgreSQL, Vue 2 and GraphQL CRUD Web App

☞ Developing and Securing GraphQL APIs with Laravel


Originally published on code-maze.com

Angular WordPress Api

How to connect WordPress API in Angular with consumer key and secreate key , curd operation in WordPress post

Integrate PHP Laravel 5.8 APIs in Angular 7

Integrate PHP Laravel 5.8 APIs in Angular 7

For PHP Laravel APIs to integrate in Angular 7, we have to write APIs in api.php file in Laravel which is in the routes folder in Laravel project structure. For the sake of this article, we are using example of User API.

we commonly use PHP Laravel 5 for database integration and Angular for frontend single page applications. So it makes sense to write about integrating PHP Laravel APIs with Angular frontend.

1. Develop Laravel API

Lets setup the database first. We follow proper Laravel structure through commands and code.

1.1 Create Laravel API migration

For PHP Laravel APIs to integrate in Angular 7, we have to write APIs in api.php file in Laravel which is in the routes folder in Laravel project structure. For the sake of this article, we are using example of User API. For User API to fetch and save data, you have to first setup database table. For that you have to write the migration for the table the command to create migration is written below.

php artisan make:migration create_user_table

After creating a migration, you have to make a model for the table that you have created. Which can be made by command written below.

1.2 Laravel model command

php artisan make:model User

short hand for creating migration and model both you will use this command

php artisan make:model User -m

After using this command the migration and model is made.

1.3 Laravel migration code example

Now you can write table in the migration. Below is the example to write table in migration.

public function up()
 {
 Schema::create('users', function (Blueprint $table) {
 $table-&gt;increments('id');
 $table-&gt;string('email')-&gt;unique();
 $table-&gt;string('first_name');
 $table-&gt;string('last_name');
 $table-&gt;string('password');
 $table-&gt;enum('account_status',['active','pending','rejected'])-&gt;default('pending');
 $table-&gt;enum('gender',['male','female']);
 $table-&gt;timestamps();
 });
 }

You can see the more about how to write table in the migration go to this link:

https://laravel.com/docs/5.7/migrations. After writing the table you have to run this command to migrate the table into the database

php artisan migrate

After migration, you have to write a method into the model that was created to get, update, or add data into the table. For an API to run you have to make,

Route::post('allUsers','[email protected]');

1. 4 Laravel controller command

php artisan make:controller UserController

1.4 Laravel controller code example

The controller function will look like this.

public function getAllUsers(){
 $count = User::All()-&gt;count();
 if($count &gt; 0){
 $users = User::role(['user','admin','dealer'])-&gt;get();
 return response()-&gt;json($users);
 }else{
 return response()-&gt;json("Users Not Found");
 }
 }

You can also make resource and collection to return the response. You can go this link and check the eloquent resources and collection https://laravel.com/docs/5.7/eloquent-resources.

So in this api the api is using UserController Method getllAllUsers to get the users from the database. After that you have to serve the laravel project to use these apis into angular project.

2. Integrate Laravel API in Angular

First setup your angular project using this command. Using Angular Cli.

ng new project_name

After that make your first component. For making component use this command.

ng generate component Users
// Or short hand:
ng g c Users

Four files will be generated after running that command. After that design your page in the html file

and in the ts file your code goes there. After that you have to make service to integrate the api calls that has been written in the Laravel so to create a service run this command.

ng generate service User
// Or short hand:
ng g s User

After running this command 2 file will be generated you will write the code in the ts file name users.service.ts there you will first import the HttpClient first. Then go to the environment folder and write the the api served url of the laravel project for local the url will look like this.

http://127.0.0.1:8000

The Laravel project will always serve on the 8000 port.

After importing the HttpClient then import the environment.ts file in the users service and get the api url from there. For importing just import the HttpClient into the constructor of the service.ts file.

After importing our service constructor will look like this.

 apiUrl: any;
constructor(private http: HttpClinet){
this.apiUrl = environment.apiUrl;
}

After that write a function to to call the API of the Laravel and we will use the HttpClient in the function an example is written below.

getAllUsers() {
 return this.http.get(this.apiUrl + 'allUsers/')
 .pipe(map((response: any) =&gt; {
 return response.json();
 }));
 }

This function is returning the data of all the users and parse then into the JSON response and return from where this function will get called.

After creating this function to get the data from the Laravel API now we will use this function into the the component that we have created first. To use the users service function import the users.service.ts file into the constructor of the users component. So this is the example to use the this service into the component.

The constructor will look like this after importing

constructor(private usersService: UsersService){
}

Here you can change the variable name for the user Service. You can set the variable name as you like. There is an ngOnInit() function in every component this is the first function to get called when ever the project gets served or this component is called. To get all the users from the service function that is calling Laravel API call to get all users the code will look like this.

allusers: any;
getUsers(){
this.usersService. getAllUsers()
.subscribe({
response =&gt; {
this.allusers=response;
},
 });
}

Here we have made first a global variable that is storing the response from the call into itself so that the response can be used the users.component.html file and anywhere in the users.component.ts file.

The getUsers function is calling the service function gellAllUsers to get the user and save it into the local variable. Now you can use this variable in whatever the way you like into your html page to show it on the webpage.

In Angular, you can also make the model to map the response also so for that you need to make a file names users.model.ts there is no specific command for that. So the model is made for the easiness to use the response of the API. Example is given below.

export class User{
 id: number;
 first_name: string;
 last_name: string;
 email: string;
 gender: string;
 status: string;
}

For mapping the response on to the model we will use Observables. Observable provide the support for passing the messages between creators of the observables and the subscribers in our application. Here the subscriber will be our getUsers function in the users.component.ts file and the Observable will be defined in the users.service.ts.

For using observers we will import the rxjs Observable into the users.service.ts file. Then after that the Observable will be used like this as shown in example below.

getUsers(): Observable&lt;{data: Users[]}&gt;{
 const headers = new HttpHeaders({'Content-Type': 'application/json'});
 return this.http.get&lt;{status_code: number, data: Users[], message: string}&gt;(this.apiUrl +
'allUsers', {headers: headers});
 }

Here the observable is parsing the response into the user model which we have created above as we are getting all the users from the API response so we are use Users[] array. And to get its parsed over here you have to format the response also in the Laravel API function. After this we also need to change the users.component.ts file so it will look like this.

 

allusers: Users[];

First we need to make your allUsers variable type to Users[] as the model and as we have done it in the service file the the gellUsers function will able to map response now.

getUsers(){
this.usersService. getAllUsers()
.subscribe({
response =&gt; {
this.allusers=response;
},
 });
}

Now it has made it easy for you to get the variable easily that are in the users model if you want to see the firstname of all the users you can easily do this

this.allusers.foreach(element =&gt;{
console.log('First Name',element.firstname);
})

as firstname is the variable that is in the model of Users.

If you follow this detailed tutorial, you can learn to write the APIs in Laravel and to integrate them in Angular project.

Thanks for reading. If you liked this post, share it with all of your programming buddies!

This post was originally published here