Angular Service in Aurelia?

萝らか妹 提交于 2019-12-08 22:01:00

问题


I've yet to find decent documentation detailing how to migrate from Angular 1.x to Aurelia. So far, I've only seen folks detailing how the concept of an Angular directive can be remade in Aurelia using @customElement. Okay, simple enough. But these examples always, always just mock data.

That said, Angular Services are singletons that can be injected into any controller/directive/service, and typically allows for the fetching of data from a server (i.e. PersonService, OrdersService).

But how are these data services modeled in Aurelia? Is everything just a class? It seems like it.

Essentially, I'd to see some code samples, a hello-world, that effectively fetches data from a service, and provides it to a @customElement. Where do the HTTP calls go? How do we even make HTTP calls? Angular uses $http, what about Aurelia?

EDIT:

Here's a simple angular service. How would one attack this in Aurelia?

app.service('SomeDataService', function () {
    return {
        getMyData: function (options) {
            return $.ajax(options);
        }
    }
});

回答1:


Yep- plain ES6/ES7 classes. There's no framework intrusion in your data services.

my-data-service.js

import {HttpClient} from 'aurelia-http-client'; // or 'aurelia-fetch-client' if you want to use fetch
import {inject} from 'aurelia-framework';

@inject(HttpClient)
export class MyDataService {
  constructor(http) {
    this.http = http;
  }

  getMyData() {
    return this.http.get(someUrl);
  }
}

fancy-custom-element.js

import {MyDataService} from './my-data-service';
import {inject} from 'aurelia-framework';

@inject(MyDataService) // aurelia's dependency injection container will inject the same MyDataService instance into each instance of FancyCustomElement
export class FancyCustomElement {
  data = null;

  constructor(dataService) {
    this.dataService = dataService;
  }

  // perhaps a button click is bound to this method:
  loadTheData() {
    this.dataService.getMyData()
      .then(data => this.data = data);
  }
}


来源:https://stackoverflow.com/questions/34295908/angular-service-in-aurelia

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!