How is an observable in angular 5 implemented in the component itself?

0

aki is my code the laravel route returns all the data of a table

import { Component, OnInit } from '@angular/core';
import { Http } from '@angular/http'
import {Observable} from 'rxjs/Observable';

import 'rxjs/add/operator/map';

@Component({
selector: 'app-main',
templateUrl: './main.component.html',
styleUrls: ['./main.component.css']
})
export class MainComponent implements OnInit {

archivo: Array<any>;


constructor(private _http: Http) { 


}


ngOnInit(){

const url = 'http://localhost/api/public/archivo';
conseguir(): Observable <Array<any>> {



return this._http.get(url).map((response) =>{

return response.json();

}).subscribe((data) => {

});

}
    
asked by ortiga 26.02.2018 в 23:03
source

1 answer

3

First of all

  • As a good practice and following the Angular Style Guide, a component should not handle HTTP requests directly, for that you should use a service.
  • For handling requests use HttpClientModule instead of HttpClient.
  • If you really need to make the request within the component (which is not recommended at all) I'll give you an example using HttpClient.
  • import {Component, OnInit} from '@ angular / core';

    import {HttpClient} from '@ angular / common / http';

    @Component({
       selector: 'app-name',
       templateUrl: './my.component.html',
       styleUrls: ['./my.component.scss']
    })
    export class MyComponent implements OnInit {
    
        apiUrl: string = 'http://localhost/api/public/archivo';
    
        constructor(private _http: HttpClient) { }
    
        ngOnInit() { }
    
        petition() {
    
            // usando observables
            this._http.get(this.apiUrl)
                .subscribe(response => {
                    let data = response['tu_propiedad'];
                    // aqui procesas tu informacion como quieras
                }, error => {
                    console.log('Algo salio mal');
                })
    
            // usando promesas
    
            this._http.get(this.apiUrl)
                .toPromise()
                .then(response => {
                    let data = response['tu_propiedad'];
                    // aqui procesas tu informacion como quieras
                })
                .catch(err => {
                    console.log('Algo salio mal', err);
                })
        }
    }
    

    Now you just have to call the petition () method where you need it

        
    answered by 27.02.2018 / 00:17
    source