错误的屏幕截图:
存在错误的代码:
import {Component, OnInit} from 'angular2/core';
import {Router} from 'angular2/router';
import {Hero} from './hero';
import {HeroService} from './hero.service';
import {RouteConfig, ROUTER_DIRECTIVES} from 'angular2/router';
import {HeroesComponent} from './heroes.component';
import {HeroDetailComponent} from './hero-detail.component';
import {DashboardComponent} from './dashboard.component';
import {SpreadSheetComponent} from './spreadsheeteditall.component';
import {SwitchUsersComponent} from './SwitchUsers.component';
import {BiddingPageComponent} from './BiddingPage.component';
import { Injectable } from 'angular2/core';
import { Jsonp, URLSearchParams } from 'angular2/http';
@Component({
selector: 'SearchAndDisplayComponent',
templateUrl: 'app/SearchDisplay.component.html',
styleUrls: ['app/SearchDisplay.component.css'],
providers: [HeroService],
directives: [ROUTER_DIRECTIVES]
})
@Injectable()
export class SearchAndDisplayComponent{
constructor(private jsonp: JSON) {}
search (term: string) {
// let ebayURL = 'http://en.wikipedia.org/w/api.php';
var params = new URLSearchParams();
params.set('search', term); // the user's search value
params.set('action', 'opensearch');
params.set('format', 'json');
params.set('callback', 'JSONP_CALLBACK');
// TODO: Add error handling
return this.jsonp
.get({ search: params })
.map(request => <string[]> request.json()[1]);
}
}
问题的背景: 我正在尝试为一个基本上是ebay克隆的网站创建一个搜索栏。
这是我之前发布的一个问题,其中包含整个项目的链接(plunker / full project zipped)
Search bar that hides results that aren't typed into it
通过点击搜索栏旁边的按钮,我试图显示它的HTML代码:
<button (click)="search(term)">Search</button>
答案 0 :(得分:0)
您需要在构造函数中注入Jsonp
类而不是JSON
类。 Jsonp对象将允许您执行JSONP请求。
import {Jsonp} from 'angular2/http';
(...)
export class SearchAndDisplayComponent{
constructor(private jsonp: Jsonp) {} // <-----
(...)
}
答案 1 :(得分:0)
JSON是javascript命名空间对象。您已从模块angular2 / http导入Jsonp,因此在yout服务的构造函数中将JSON更改为Jsonp。并且不要忘记将Jsonp提供程序添加到组件层次结构上面的某个组件。