Angular service not working with http.get observable

霸气de小男生 提交于 2019-12-22 18:59:08

问题


I am trying to retrieve json file from the server using http.get and subscribe to the observable from a component. However, it's returning an error, not the data.

Can you please tell me where I'm going wrong:

import { Injectable } from '@angular/core';
import { Http } from '@angular/http';
import { Observable } from 'rxjs';

@Injectable()
export class MoviesService {

  constructor(private http: Http) {
  }

  getMovies() : Observable<any> {
    let url = API_URL;
    return this.http.get(url);
  }
}

and here's the component:

import { Component } from '@angular/core';
import { MoviesService } from './movies.service';

@Component({
  selector: 'movies',
  templateUrl: './movies.component.html',
  styleUrls: ['./movies.component.css'],
  providers: [
    MoviesService
  ]
})

export class MoviesComponent {

  constructor(private moviesService: MoviesService) {};

  ngOnInit() {
    this.moviesService.getMovies().subscribe(
      (data: any) => {
        console.log("Success " + data);
      },
      (err) => {
        console.log("Error: " + JSON.stringify(err));
      }
    );
  }
}

I'm using latest versions of Angular and rxjs library.

Please help.


回答1:


Use HttpClient instead of Http. Http returns an Object of type Response. You'll have to call the json() method on it which will give you the data that you're looking for.

To avoid doing that, use HttpClient. And to use HttpClient, you'll have to first add HttpClientModule to the imports array of your module.

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs';

@Injectable()
export class MoviesService {

  constructor(private http: HttpClient) {
  }

  getMovies() : Observable<any> {
    let url = API_URL;
    return this.http.get(url);
  }
}

Update

Your API isn't secure. That's why the client is blocking it and giving a mixed content error. This generally happens when some of your content is served over HTTPS and some are served over HTTP. I don't really think there's a way to fix this without changing the API.

You should consider using an secure API for movies.

You can use OMDb API. It's a Secure and Free API to get movie details. You'll have to create an API Key first. You can do that here.



来源:https://stackoverflow.com/questions/52136831/angular-service-not-working-with-http-get-observable

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!