httpclient google in typescript

To use HttpClient in Typescript to make a request to Google, first, we need to install the @angular/common/http package by running the following command in our terminal:

index.ts
npm install @angular/common@latest --save
42 chars
2 lines

After installing the package, we can create an instance of HttpClient in our Typescript file and use the get() method to make a request to Google. Here is an example:

index.ts
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';

@Injectable({
  providedIn: 'root'
})
export class GoogleService {

  constructor(private http: HttpClient) { }

  getGoogleContent() {
    return this.http.get('https://www.google.com');
  }
}
290 chars
15 lines

In the code above, we first import the HttpClient from the @angular/common/http package, then create an instance of HttpClient in our GoogleService class constructor. We then define a getGoogleContent() method that returns a call to get() method of HttpClient and passes the URL of Google as an argument.

Now, we can use this service in our component by injecting it in the constructor and calling the getGoogleContent() method. For example:

index.ts
import { Component } from '@angular/core';
import { GoogleService } from './google.service';

@Component({
  selector: 'app-root',
  template: `
    <div>{{content}}</div>
  `,
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  content: string;

  constructor(private googleService: GoogleService) {}

  ngOnInit() {
    this.googleService.getGoogleContent().subscribe((res: string) => {
      this.content = res;
    });
  }
}
447 chars
22 lines

In the code above, we import the GoogleService and inject it in the constructor. We then call the getGoogleContent() method and subscribe to the observable to get the response, which is assigned to the content variable that is displayed in the template.

That's it, now you can use HttpClient in Typescript to make a request to Google.

related categories

gistlibby LogSnag