Httpclient at Angular 4

Asked

Viewed 83 times

2

Guys, I need help with Angular 4... I need to consume an api (json-server)... for testing, I put the content of Json directly in the code, as below... but now I need to replace it with the address of the api (localhost:port/communiqué).

Can someone tell me how to do this?

It’s all set up. I just need to know how to enter the server address. I’ve been searching since 5am but no results.

I appreciate anyone who can give me some guidance.

import { HttpClient } from "@angular/common/http"
import { Injectable } from '@angular/core'
import { Comunicados } from './shared/comunicados.model'

@Injectable()
export class ComunicadosService {

constructor(private http: HttpClient){}

public comunicados: Comunicados[] = [
    {
"id": 1,
"title": "Titulo",
"seen": false,
"type": 0,
"description": "descricao.",
"fullDescription": "AAA",
"date": "2013-05-03 8:30"
 },
}

public getComunicados(): Array<Comunicados> {
    return this.comunicados
}
}
  • 2

    where’s your call code ajax?

  • Thank you for the reply, @Ricardopontual This is the contents of the module file: https://pastebin.com/zx87Jegv

  • 1

    Bruno, if you also have the javascript part that makes the call to the service helps us understand what is not working

  • I’m actually using Typescript, Ricardo. The above code already works with the data of the json entered. But I need to remove this json that I pasted and use a URL from a Fake Api, you know?

  • 1

    So, "but now I need to replace this with the api address" to do this you need a call ajax, you’ve even injected the dependency of HttpClient but is missing use to call the api, this is missing in your code

  • You can do so: http.get(URL) . map(res => res.json()) . subscribe(data => console.log(date);

Show 1 more comment

2 answers

3


After a little more research and carefully handles the A4 documentation, solved with:

(...)
import { END_API } from '../app.api'
import 'rxjs/add/operator/map'

@Injectable()
export class ComunicadosService {

constructor(private http: HttpClient){}

comunicados(): Observable<Comunicado[]> {
    return this.http.get<Comunicado[]>(`${END_API}/link`);
}
}

Thanks to Lucas and Ricardo, who helped a lot!

  • 1

    the use of the subscribe(), according to the angular documentation no request http is called until the use of this function.

2

You can make the request like this:

http.get(insere a url da api aqui)
.map(res => res.json())
.subscribe(data => console.log(data));
  • Oops! Thanks for the answer, Lucas! = ) From what I could understand here, the . map(...) is no longer used.

  • The use of the map is relative. It really is not a requirement hehe.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.