使用四角api角2 2

使用四角api角2 2

问题描述:

我有问题搞清楚如何在我的角2应用程序中使用foursquare api (search capability)使用四角api角2 2

我的项目结构看起来像这样

app 
    components 
    app.ts 
    search.ts 
    services 
    foursquare.ts 
    typings 
    boot.ts 
index.html 

foursquare.ts看起来像这样

import {Injectable, Inject} from 'angular2/core'; 
import {Http, Response, RequestOptions, Headers, Request, RequestMethod} from 'angular2/http'; 

import 'rxjs/add/operator/map'; 

const CLIENT_ID = 'My client id'; 
const SECRET = 'My secret'; 
const URL : string = 'https://api.foursquare.com/v2/venues/search?client_id='+CLIENT_ID+'&client_secret='+SECRET+'&v=20130815'; 

@Injectable() 
export class FoursquareService { 

constructor(public http:Http) { 
    this.http = http; 
} 

foursquareGet(data) { 
    return this.http.get(URL+data).map(res => res.json()); 
} 
} 

而且我想在接下来的方式

search.ts使用
import {Component} from 'angular2/core'; 
import {FoursquareService} from '../../services/foursquare' 

@Component({ 
    templateUrl : 'app/components/new-listing/new-listing.html', 
    providers : [FoursquareService] 
}) 

export class NewListingComponent { 
    constructor(service : FoursquareService) { 
    console.log(service.foursquareGet('&ll=40.7,-74&query=sushi')); 
    } 
} 

这会返回控制台内的Observable,我不知道如何使用,并且希望它返回符合条件的json对象数组。我试图按照这方面的文档,但不知道接下来要做什么。

是的,get mezthod的Http类返回一个可观察的。你可以明确地订阅它,你的模板中使用结果:

export class NewListingComponent { 
    constructor(service : FoursquareService) { 
    service.foursquareGet('&ll=40.7,-74&query=sushi') 
     .subscribe(data => { 
     this.result = data; 
     }); 
    } 
} 

您还可以通过利用async管,让它处理的可观察走得更远。在这种情况下,您可以设置观察为您的组件的属性:

@Component({ 
    template: ` 
    <ul> 
     <li *ngFor="#elt of result | async">{{elt.something}}</li> 
    </ul> 
    ` 
}) 
export class NewListingComponent { 
    constructor(service : FoursquareService) { 
    this.result = service.foursquareGet('&ll=40.7,-74&query=sushi'); 
    } 
} 

这个答案可以给你更多的提示在此:How to Consume Http Component efficiently in a service in angular 2 beta?

希望它可以帮助你, 蒂埃里

+0

哪里可以正确定义结果变量? – Ilja

+0

既然你想在你的组件中使用它,它必须是它的一部分。我的意思是一个类属性。它隐含在我提供的代码中。但是你可以明确地定义它:'result:ResultClass [];'直接在'export class NewListingComponent'行的下面。 –

+0

我明白了,在最后一个问题中,我假设需要为RequestClass添加一个导入? – Ilja

使用订阅:

service.foursquareGet('&ll=40.7,-74&query=sushi').subscribe(data=> this.data=data); 
+0

引发数据错误(在类型NewListingComponent不存在) – Ilja

+0

定义数据作为成员变量,或做其他事吧。 – pixelbits