本文介绍了从查询字符串中获取数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试从以下URL获取数据: https://api.chucknorris.io/jokes/search?query=chuck (查克是搜索词,也可以是其他任何词.)

I'm trying to fetch data from this URL:https://api.chucknorris.io/jokes/search?query=chuck(chuck is the search term, it can be anything else).

我想从数组中获取value属性.邮递员给我这个消息:

I want to get the value property from the array. Postman gets me this:

{
"total": 9735,
"result": [
{
  "category": [
    "dev"
  ],
  "icon_url": "https://assets.chucknorris.host/img/avatar/chuck-norris.png",
  "id": "zdj0bfkjsmup6pkb2rpmbw",
  "url": "http://api.chucknorris.io/jokes/zdj0bfkjsmup6pkb2rpmbw",
  "value": "Chuck Norris is the only human being to display the Heisenberg
  uncertainty principle - you can never know both exactly where and how
  quickly he will roundhouse-kick you in the face."
 },

我的服务(已编辑):

import { HttpModule } from '@angular/http';
import { Injectable } from '@angular/core';
import { Http } from '@angular/http';
import 'rxjs/add/operator/map';
import { Joke } from '../joke'

@Injectable()
export class PretragaService {
constructor(private http: Http){}
searchJokes(str: string){return
this.http.get('https://api.chucknorris.io/jokes/search?query=' + str)
                    .map(res => res.json())
                    .map(joke => {return joke.value});
}

}

组件(已编辑):

import { Component } from '@angular/core';
import { PretragaService } from '../services/pretraga.service';

@Component({
selector: 'pretraga',
template: `
<input type="text" class="form-control" placeholder="pretraži"
[(ngModel)]="searchJoke"
name="searchJoke" (keyup)="searchJokes()">
<div *ngIf="searchRes">
<div *ngFor="let joke of searchRes">
<ul>
<li>{{joke}}</li>
</ul>
</div>
</div>
`,
providers: [PretragaService]
})
export class PretragaComponent {
searchJoke: string;
searchRes: any[]=[];

constructor(private searchService: PretragaService){

}
searchJokes(){
   this.searchService.searchJokes(this.searchJoke)
   .subscribe(joke => {
   this.searchRes = joke;
});
}

我有代表一个对象的类:

I have the class that represents an object:

export class Joke{
value: string;

}

推荐答案

//修改myService类:

// Modify your myService class :

    searchJokes(str: string){return
    this.http.get('https://api.chucknorris.io/jokes/search?query=' + str)
                        .map(res => res.json())
                        .map(joke => {return joke.value});
    }

//和component:

// and component :

    searchJoke: string;
    searchRes: any[]=[];

    constructor(private searchService: PretragaService){

    }
    searchJokes(){
       this.searchService.searchJokes(this.searchJoke)
       .subscribe(joke => {
       this.searchRes = joke;
    });

这篇关于从查询字符串中获取数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

06-26 07:31