【问题标题】:Http.Get() always returning undefined in angular 2Http.Get() 总是在角度 2 中返回 undefined
【发布时间】:2017-04-17 17:56:04
【问题描述】:

按照教程,讲师正在使用 spotify api 构建 Spotify 音乐搜索。遵循教练所做的每一步,但问题是我的数据永远不会回来,我没有定义,屏幕上什么也没有。但是,如果我直接在浏览器中点击 api,则会显示 json 数据,但不会显示在我的应用中。

其实我见过很多这样的问题,但没有一个能解决我的问题。我认为这可能是与网络相关的问题,但是当我设置断点时,我可以在响应中看到结果,但没有任何内容加载到视图中,未定义正在加载到控制台中

**search.component.html**
<h1>Need Music?</h1>
<p class="lead">
  Use the ngSpotify app to browse new releases of your favorite songs. See what your favorite artistes are up to.
</p>
<form>
  <div class="form-group">
    <input type="text" name="searchStr" [(ngModel)]="searchStr" (keyup.enter)="searchMusic()" class="form-control" placeholder="Search music here..."/>
  </div>
</form>

**search.component.ts**
import { Component, OnInit } from '@angular/core';
import { SpotifyService } from '../../Services/spotify.service';  
@Component({
  selector: 'app-search',
  templateUrl: './search.component.html',
  styleUrls: ['./search.component.css']
})
export class SearchComponent implements OnInit {

  constructor(private _spotifyservice: SpotifyService) { }

  searchStr: string;
  searchResult;

  searchMusic() {
    return this._spotifyservice.searchMusic(this.searchStr)
      .subscribe(data => {
        console.log(data);
        this.searchResult = data;
       },
        error => {
          console.log(error)
        })
      }    

  ngOnInit() {
  }

}

**spotify.service.ts**
import { Injectable } from '@angular/core';
import { Http, Response, Headers } from '@angular/http';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/catch';

import { Observable } from 'rxjs/Rx'


@Injectable()
export class SpotifyService {
  private searchUrl: string;

  constructor(private _http: Http) { }

  searchMusic(str: string, type = 'artist') {
    this.searchUrl = `http://api.spotify.com/v1/search?query=${str}&offset=0&limit=20&type=${type}&market=US`

    return this._http.get(this.searchUrl)
      .map((res) => { res.json() })
      .catch(this.handleError);

  }

  handleError(error: Response) {
    return Observable.throw(error || 'server error');
  }
}

【问题讨论】:

    标签: angular angular2-services angular-http angular2-observables


    【解决方案1】:

    既然你是这样映射的:

    .map((res) => { res.json() })
    

    你需要使用return

    .map((res) => { return res.json() })
    

    或仅使用:

    .map(res => res.json())
    

    DEMO

    【讨论】:

      【解决方案2】:

      您的 [(ngModel)] 在这种情况下将不起作用,因此您需要使用 ElementRef 来引用输入文本框

      <input type="text" name="searchStr" #input (keyup.enter)="searchMusic(input.value)" class="form-control" placeholder="Search music here..."/>
      

      修改你的方法为

      searchMusic(searchStr:string) {
          return this._spotifyservice.searchMusic(searchStr)
            .subscribe(data => {
              console.log(data);
              this.searchResult = data;
             },
              error => {
                console.log(error)
              })
            }   
      

      在你的组件中声明一个元素 ref 为

      @ViewChild('input') input: ElementRef;
      

      【讨论】:

        猜你喜欢
        • 2017-12-01
        • 2017-03-18
        • 2016-01-16
        • 1970-01-01
        • 2017-05-21
        • 2012-09-05
        • 2019-06-27
        • 2015-08-11
        • 2014-07-30
        相关资源
        最近更新 更多