Send data from service to observable Get request

后端 未结 2 332
自闭症患者
自闭症患者 2021-01-27 21:42

I am new to Angular and Observables. I have a service that receives a URL I want to pass to my observable and render data every time a new URL is passed to it with NgFor. Any ex

2条回答
  •  太阳男子
    2021-01-27 22:28

    // This sample using angular 9/10
    // Component name:  list.component.ts
    
    import { HttpClient } from '@angular/common/http';
    import { Component, OnInit } from '@angular/core';
    import { NgZone} from '@angular/core';
    import {HttpServiceService} from './../http-service.service';
    
    @Component({
      selector: 'app-list',
      templateUrl: './list.component.html',
      styleUrls: ['./list.component.scss']
    })
    export class ListComponent implements OnInit {
    
      constructor(
         private http: HttpServiceService,
         private zone: NgZone
        ) { }
      brews: object;
      ngOnInit(): void {
          this.http.getPeople().subscribe(data => {
          this.brews = data;
          alert(JSON.stringify(this.brews));
          console.log(this.brews);
          });
      }
    }
    //--------------------------------
    
    // This is my http service
    // Component Name: http-service.service.ts
    
    import { Observable, of } from 'rxjs';
    import { Injectable } from '@angular/core';
    
    @Injectable({
      providedIn: 'root'
    })
    export class HttpServiceService {
    
      constructor() { }
      getPeople(): Observable{
        const myNameArray = [{
          firstName: 'Algem',
          lastName: 'Mojedo',
          age: 63
        }];
        return of(myNameArray);
     }
    }
    
    //--------------------------
    // should display in alert
    
    localhost:4200 says
    [{"firstName":"Algem","lastName":"Mojedo","age":"60"}]
    
    Happy coding..
    

提交回复
热议问题