简体   繁体   English

在组件功能内使用angular 2服务

[英]Use angular 2 services within functions of components

Here is an example of how I'm getting foursquare information within one of my components: 这是一个如何在一个组件中获取四方信息的示例:

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);
    });

  }

}

This logs related objects to console on page load, however I want to achieve same functionality on click of a button or while users are typing, hence have it in separate function, however every time I remove foursquareApi : FoursquareService from constructor I get various errors. 这会将相关对象记录到页面加载时的控制台上,但是我想在单击按钮时或在用户键入时实现相同的功能,因此将其放在单独的功能中,但是每次我从构造函数中删除foursquareApi : FoursquareService ,我都会遇到各种错误。

You can add a listener (with the (click) expression) in your template that uses a method of your component (the loadData one for example): 您可以在模板中使用组件方法(例如loadData一个)添加一个侦听器(带有(click)表达式):

@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);
    });
  }
}

Hope it helps you, Thierry 希望对您有帮助,蒂埃里

You should make the foursquareApi a member of the class (private/public/protected). 您应该使foursquareApi成为该类的成员(私有/公共/受保护)。 Otherwise it is not accessible outside the constructor. 否则,将无法在构造函数外部访问它。

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);
    });
  }

}

I'll add some insight to my answer. 我将在我的答案中添加一些见解。

You can leave the FourSquareService in your constuctor because you want it to instantiated when your component is rendered. 您可以将FourSquareService保留在构造器中,因为您希望在呈现组件时实例化它。

Just move your logic to an other function like so. 只需将您的逻辑移至其他函数即可。

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);
    });
  }

}

Make the service protected in constructor and do whatever call with the service in constructor for on load. 使服务在构造函数中受保护,并在装入时对构造函数中的服务进行任何调用。

When you want to use for onClick or some action you can refer to the service inside onClick function . 当您想用于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);
 }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 编写全局函数以在角度的所有组件中使用 - Write global functions to use in all components in angular Angular 5 全局组件及其服务 - Angular 5 global components and their services 在 Angular Singleton 服务中取消订阅? - Unsubscribing within Angular Singleton Services? 管理 Angular 服务和组件之间的订阅 - Manage subscriptions between Angular services and components Angular 组件与后端服务之间的通信 - Communication between Angular components and backend services 访问 Angular 7/8 布局组件和服务中的路由参数? - Accessing route parameters in Angular 7/8 layout components and services? 在Angular中处理服务和组件之间的异步数据 - Handling asynchronous data between services and components in Angular 通过Angular Services在Angular组件之间路由Subject的Angular 4/5问题 - Angular 4/5 issue with routing Subject between Angular components via Angular Services 在 React 组件中定义函数有什么好处吗? - Are there any benefits to defining functions within React components? Angular 2:我如何使用角度动画淡入/淡出其中的组件<router-outlet>在初始加载之后? - Angular 2: How do I use angular animations to fade in/fade out of components within <router-outlet> after the initial load?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM