我陷入了可能非常基本的事情......我只需要调用一个网络服务器并获取我的结果。在 Angular 1 中它曾经很容易。
这是我调用服务的组件:
import {Component, Input, OnChanges} from "angular2/core";
import {SearchService} from "../../../services/search.service";
@Component({
selector: "typeahead",
providers: [SearchService],
template: `
{{searchSvc | json}}
`,
})
export class TypeaheadComponent implements OnChanges {
@Input() txt: string;
display = false;
searchSvc;
ngOnChanges(changes: { [propName: string]: SimpleChange }) {
var search = changes['txt'].currentValue;
if (search.length > 2) {
this.display = true;
this.searchSvc = this._searchService.DoGeneralSearch();
}
else {
this.display = false;
}
}
constructor(private _searchService: SearchService) {
}
}
这是我正在使用的服务:
import {Injectable, OnInit} from 'angular2/core';
import {Http, HTTP_PROVIDERS, Response} from 'angular2/http';
import 'rxjs/add/operator/map';
@Injectable()
export class SearchService implements OnInit {
generalSearchResults;
ngOnInit() {
this.DoGeneralSearch();
}
constructor(private _http: Http) {
}
DoGeneralSearch() {
this._http.get('http://localhost:7000/search?q=chem')
.map((res: Response) => res.json())
.subscribe(
data => {
this.generalSearchResults = data
},
err => console.log(err),
() => console.log(this.generalSearchResults)
)
}
}
基本上我只想看到我的结果显示在我的模板中。当 () => console.log(this.generalSearchResults) 被调用时,我可以看到结果,我在控制台上注意到了这一点。我看到结果,结果是正确的,json对象是正确的。
可能有什么问题或遗漏?