我正尝试将Ionic 2应用程序连接到Yelp的API。现在我只是使用从CLI生成并运行在本地主机上的空白Ionic 2应用程序。Ionic 2 Yelp API
我的代码:
app.module.ts
import { BrowserModule } from '@angular/platform-browser';
import { ErrorHandler, NgModule } from '@angular/core';
import { HttpModule } from '@angular/http';
import { IonicApp, IonicErrorHandler, IonicModule } from 'ionic-angular';
import { SplashScreen } from '@ionic-native/splash-screen';
import { StatusBar } from '@ionic-native/status-bar';
import { MyApp } from './app.component';
import { HomePage } from '../pages/home/home';
@NgModule({
declarations: [
MyApp,
HomePage
],
imports: [
BrowserModule,
HttpModule,
IonicModule.forRoot(MyApp)
],
bootstrap: [IonicApp],
entryComponents: [
MyApp,
HomePage
],
providers: [
StatusBar,
SplashScreen,
{provide: ErrorHandler, useClass: IonicErrorHandler}
]
})
export class AppModule {}
home.ts
import { Component } from '@angular/core';
import { NavController } from 'ionic-angular';
import { Http } from '@angular/http';
import { Headers, RequestOptions } from '@angular/http';
import 'rxjs/add/operator/map';
@Component({
selector: 'page-home',
templateUrl: 'home.html'
})
export class HomePage {
restaurants:any;
constructor(public navCtrl: NavController, public http: Http) {
var headers = new Headers();
headers.append('Authorization', 'Bearer someString');
var options = new RequestOptions({headers: headers});
this.http.get('https://api.yelp.com/v3/businesses/search?term=deli20&latitude=39.59754&longitude=-104.872934', options).map(res => res.json()).subscribe(data => {
this.restaurants = data.data.children;
console.log(this.restaurants);
});
}
}
home.html
<ion-header>
<ion-navbar>
<ion-title>
Ionic Blank
</ion-title>
</ion-navbar>
</ion-header>
<ion-content padding>
The world is your oyster.
<p>
If you get lost, the <a href="http://ionicframework.com/docs/v2">docs</a> will be your guide.
</p>
<!--Just using Ionic 2's default home page, just wanna output my JSON to the console for now.-->
</ion-content>
页面呈现correc TLY,但我在控制台中出现错误:“无法加载资源:预检响应不成功”
的回应是这样的:
{"error": {"code": "TOKEN_MISSING", "description": "An access token must be supplied in order to use this endpoint."}}
什么我可能会丢失有什么想法?
看起来像你需要在HTTP头中提供访问令牌 - 查看更多:https://github.com/Yelp/yelp-fusion/issues/45 – NickyTheWrench
这就是我以为我是使用: var headers = new Headers(); headers.append('Authorization','Bearer someString'); var options = new RequestOptions({headers:headers}); – user3183717
你用你的实际令牌代替了“someString”,对吧? – NickyTheWrench