Generując nowy projekt poprzez Angular CLI, pojawia się do wyboru rodzaj styli:
Wykonanie promptera jest wyjątkowo proste. Załóżmy, że użytkownik tworząc serwis, może wybrać responseType, np. text:
1 2 3 |
getFlight(): Observable<Flight> { return this.http.get<Flight>(ENDPOINTS.GET_FLIGHT, {responseType: 'text'}); } |
Wybór jest ograniczony do 4 wartości: text, arraybuffer, blob i json (domyślny). Jest to dobra okazja, aby pomóc użytkownikowi z wyborem poprzez zaprezentowanie opcji do wyboru.
Przechodzimy do pliku schema.json i dodajemy nową pozycję o nazwie responseType:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
{ "$schema": "http://json-schema.org/schema", "id": "AngularLoveHttpServiceSchematic", "title": "Creates a httpService Schematic.", "type": "object", "properties": { ... "responseType": { "type": "string", "description": "Specifies the responseType for http methods", "default": "json", "x-prompt": { "message": "Which responseType would you like to use?", "type": "list", "items": [ { "value": "json", "label": "JSON (default)" }, { "value": "text", "label": "TEXT" }, { "value": "arraybuffer", "label": "ARRAY BUFFER" }, { "value": "blob", "label": "BLOB" } ] } } } } |
Powyższy kod jest bardzo intuicyjny i myślę, że właściwie nie ma co tu wyjaśniać. Kluczem jest właściwość „x-prompt” z odpowiednią listą. Efekt w konsoli:
Pozostaje nam jeszcze zmodyfikować templatkę:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
import { Injectable } from '@angular/core'; import { HttpClient } from '@angular/common/http'; import { Observable } from 'rxjs'; const ENDPOINTS = { GET_<%= classify(name.toUpperCase()) %>: '', }; @Injectable({providedIn: 'root'}) export class <%= classify(name) %>Service { constructor(private http: HttpClient) {} <% if (methods.includes('get')) { %> get<%= classify(capitalize(name)) %>(): Observable<<%= classify(capitalize(name)) %>[]> { return this.http.get<<%= classify(capitalize(name)) %>[]>(ENDPOINTS.GET_<%= classify(name.toUpperCase()) %><% if (responseType !== 'json') { %>, { responseType: '<%= responseType %>' }<% }%>); }<% } %> } |
Wołamy komendę i wybieramy z listy „text”:
1 |
ng g angularlove:http-service drink |
Efekt:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
import { Injectable } from '@angular/core'; import { HttpClient } from '@angular/common/http'; import { Observable } from 'rxjs'; const ENDPOINTS = { GET_DRINK: '', }; @Injectable({providedIn: 'root'}) export class DrinkService { constructor(private http: HttpClient) {} getDrink(): Observable<Drink[]> { return this.http.get<Drink[]>(ENDPOINTS.GET_DRINK, { responseType: 'text' }); } } |
Kod:
https://github.com/tomasznastaly/angular-schematics-tutorial/pull/8/files14