简体   繁体   中英

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. 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

You do not inject the http instance into your constructor and Angular relies on dependency injection . Add the following and make sure the main module has the http module registered so you can use them for DI . Remove your current http variable from the class definition.

constructor(private http: Http) {}

In your application module make sure you import HttpModule from '@angular/http'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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