Angular Service in Aurelia?

2019-06-19 17:23发布

问题:

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