Angular服务无法与http.get observable一起使用
我正在尝试使用http.get从服务器检索json文件,并从组件订阅可观察的内容.但是,它返回的是错误,而不是数据.
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);
}
}
这是组件:
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));
}
);
}
}
我正在使用Angular和rxjs库的最新版本.
I'm using latest versions of Angular and rxjs library.
请帮助.
使用HttpClient代替Http
. Http
返回类型为Response
的对象.您必须在其上调用json()
方法,该方法将为您提供所需的数据.
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.
为避免这样做,请使用HttpClient
.要使用HttpClient
,您必须首先将HttpClientModule
添加到模块的imports
数组中.
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);
}
}
更新
您的API不安全.这就是客户端阻止它并给出混合内容错误的原因.通常,当您的某些内容通过HTTPS提供服务,而某些内容通过HTTP提供服务时,就会发生这种情况.我真的不认为有一种方法可以在不更改API的情况下解决此问题.
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.
您应该考虑对电影使用安全的API.
You should consider using an secure API for movies.
您可以使用 OMDb API .这是一个安全免费的API,可获取电影详细信息.您必须先创建一个API密钥.您可以在此处进行操作.
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.