简体   繁体   English

使用Angular可观察和http

[英]Use Angular observable and http

I try to learn more about Observable and i use them for get some json data from a url but i have some issue with get method. 我尝试了解有关Observable的更多信息,并且我使用它们来从URL获取一些json数据,但是我对get方法有一些疑问。 also i want to know if there is another solution for this matter. 我也想知道是否有另一种解决方案。

import { Component , ViewChild , AfterViewInit } from '@angular/core';
import {Observable} from 'rxjs/Rx';
import {Http} from '@angular/http';
@Component({
selector: 'app-root',
template: `<h1>Hello World!</h1>
            <input type="text" #name >
            `,


})

export class AppComponent implements AfterViewInit{ 
@ViewChild ('name') input;

constructor(private http: Http){}

ngAfterViewInit(){

    var keyup = Observable.fromEvent(this.input.nativeElement,"keyup")
                          .map((data: any) => data.target.value)
                          .filter(text => text.length >= 3)
                          .distinctUntilChanged()
                          .debounceTime(400)
                          .flatMap(result => {
                             var url = "https://freemusicarchive.org/api/trackSearch?limit=10&q="+result;
                             var res = this.http.get(url).map(data => {data.json()});
                             return res
                          });
    keyup.subscribe(data => console.log(data));
}
}

Cannot read property 'get' of undefined 无法读取未定义的属性“ get”

You do not inject the http instance into your constructor and Angular relies on dependency injection . 您无需将http实例注入到构造函数中,而Angular依赖于依赖项注入 Add the following and make sure the main module has the http module registered so you can use them for DI . 添加以下内容,并确保主模块已注册http模块,以便可以将其用于DI Remove your current http variable from the class definition. 从类定义中删除当前的http变量。

constructor(private http: Http) {}

In your application module make sure you import HttpModule from '@angular/http' 在您的应用程序模块中,确保从'@angular/http'导入HttpModule

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM