【问题标题】:Use angular 2 services within functions of components在组件的功能中使用 Angular 2 服务
【发布时间】:2018-06-01 11:56:06
【问题描述】:

这是我如何在我的一个组件中获取四方信息的示例:

import {Component} from 'angular2/core';
import {FoursquareService} from '../../services/foursquare'

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

export class NewListingComponent {

  venues : Array<Object> = [];

  constructor(foursquareApi : FoursquareService) {

    //Foursquare api
    foursquareApi.foursquareGet('&ll=51.5255168,-0.0858669&query=xoyo')
    .subscribe(data => {
      this.venues = data.response.venues;
      console.log(this.venues);
    });

  }

}

这会在页面加载时将相关对象记录到控制台,但是我想在单击按钮或用户键入时实现相同的功能,因此将其放在单独的函数中,但是每次我从构造函数中删除 foursquareApi : FoursquareService各种错误。

【问题讨论】:

    标签: javascript angular service


    【解决方案1】:

    我会在我的回答中添加一些见解。

    您可以将 FourSquareService 留在您的构造函数中,因为您希望在渲染组件时实例化它。

    只需将您的逻辑移至其他函数即可。

    import {Component} from 'angular2/core';
    import {FoursquareService} from '../../services/foursquare'
    
    @Component({
      templateUrl : 'app/components/new-listing/new-listing.html',
      providers : [FoursquareService]
    })
    
    export class NewListingComponent {
    
      venues : Array<Object> = [];
    
      // this assigns _foursquareApi as a private property for the 
      // NewListingComponent and is available later in your userSubmission function.
      constructor(private _foursquareApi : FoursquareService) {}
    
      // function you want to be called on click or submission.
      userSubmission(submittedData:string){
        //Foursquare api
        this._foursquareApi.foursquareGet(submittedData)
        .subscribe(data => {
          this.venues = data.response.venues;
          console.log(this.venues);
        });
      }
    
    }
    

    【讨论】:

      【解决方案2】:

      您可以在模板中添加一个侦听器(使用(click) 表达式),该侦听器使用组件的方法(例如loadData):

      @Component({
        template : `
          <span (click)="loadData()">Load data</span>
          <ul>
            <li *ngFor="#venue of venues">{{venue.something}}</li>
          </ul>
        `,
        providers : [FoursquareService]
      })
      export class NewListingComponent {
        venues : Array<Object> = [];
      
        constructor(foursquareApi : FoursquareService) {
          this.foursquareApi = foursquareApi;
        }
      
        loadData() {
          //Foursquare api
          this.foursquareApi.foursquareGet('&ll=51.5255168,-0.0858669&query=xoyo')
            .subscribe(data => {
              this.venues = data.response.venues;
              console.log(this.venues);
          });
        }
      }
      

      希望对你有帮助 蒂埃里

      【讨论】:

        【解决方案3】:

        您应该让foursquareApi 成为该类的成员(私有/公共/受保护)。否则它在构造函数之外是不可访问的。

        import {Component} from 'angular2/core';
        import {FoursquareService} from '../../services/foursquare'
        
        @Component({
          templateUrl : 'app/components/new-listing/new-listing.html',
          providers : [FoursquareService]
        })
        
        export class NewListingComponent {
        
          venues : Array<Object> = [];
        
          //try to keep the constructor body as empty as possible
          //as you can see i've added the word 'public' 
          constructor(public foursquareApi : FoursquareService) {} 
        
          public getFourSquare() : void {
            //Foursquare api
            this.foursquareApi.foursquareGet('&ll=51.5255168,-0.0858669&query=xoyo')
            .subscribe(data => {
              this.venues = data.response.venues;
              console.log(this.venues);
            });
          }
        
        }
        

        【讨论】:

          【解决方案4】:

          使服务在构造函数中受到保护,并在构造函数中对服务进行任何调用以进行加载。

          当你想使用onClick或者一些动作时,你可以参考onClick函数里面的服务。

           constructor(private myService: MyService) { //Do call with on load for this.
           }
           toggleHobbies() {
             this.showHobbies = !this.showHobbies;
             console.log(this.myService.getPosts());
             console.log(1);
           }
          

          【讨论】:

            猜你喜欢
            • 2020-01-11
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2017-06-12
            • 2018-06-22
            • 2021-09-08
            • 1970-01-01
            • 2015-08-05
            相关资源
            最近更新 更多