【问题标题】:Angular 2 Basic http service requestAngular 2 基本 http 服务请求
【发布时间】:2016-03-10 09:14:19
【问题描述】:

我遇到了一些可能非常基本的问题...我只需要调用一个 Web 服务器并获取我的结果。在 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对象是正确的。

可能有什么问题或遗漏?

【问题讨论】:

    标签: angular angular2-services angular2-http


    【解决方案1】:

    您需要从您的 DoGeneralSearch 返回 observable 并改为订阅组件:

    export class SearchService {
      constructor( private _http: Http ) {
      }
    
      DoGeneralSearch(){   
        return this._http.get('http://localhost:7000/search?q=chem')
         .map((res:Response) => res.json());
      }
    }
    

    为此,您可以利用async 管道:

    @Component({
      selector: "typeahead",
      providers: [SearchService],
      template : `
        {{searchSvc | async | json}}
      `
    })
    export class TypeaheadComponent implements OnChanges {
      @Input() txt: string;
      display = false;
    
      constructor(private _searchService: SearchService) {
      }
    
      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;
        }
      }
    }
    

    【讨论】:

    • 嗨,蒂埃里!我根据您的建议做了以下更改:在我的 this._http 和异步管道之前返回。结果: [ res: {{searchSvc |异步 | json}} 在 TypeaheadComponent@1:59] 中。没有异步,我有这个错误:TypeError: Converting circular structure to JSON in [ res: {{searchSvc | json}} 在 TypeaheadComponent@1:59] 并且没有 json 和没有异步我没有得到任何错误,但是 [object Object] 代替:(
    • 没关系..我没有注意到您对我的服务进行了更改!现在它的作品!
    • 太棒了!是的,您需要从您的服务中返回 observable,并且不再在此级别订阅...
    【解决方案2】:
    export class SearchService {
      constructor( private _http: Http ) {
      }
    
      DoGeneralSearch(){   
        return this._http.get('http://localhost:7000/search?q=chem')
         .map((res:Response) => res.json());
      }
    }
    
    
    
    this._searchService.DoGeneralSearch
                       .subscribe(res=>{
                           this.searchSvc =res;  //make sure you get required data here.
                           console.log('bye');
                        },
                        (err)=>console.log(err),
                        ()=>console.log("Done")
                        );
    

    【讨论】:

    • 无论如何,mycronyks !
    • 干杯!在 angular2 中快乐编码。
    猜你喜欢
    • 2016-04-03
    • 2018-03-16
    • 1970-01-01
    • 2016-05-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-11-29
    相关资源
    最近更新 更多