How to store the root url of api in angular 4 app?

后端 未结 7 1499
Happy的楠姐
Happy的楠姐 2020-12-29 03:16

I followed the official tutorials and made services for the Apis but absolute url of the Api is hardcoded in services.

I want to keep the base url of Api somewhere s

7条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-12-29 04:04

    export class AppSettings {
       public static API_ENDPOINT='http://127.0.0.1:6666/api/';
    }
    

    And then in the service:

    import {Http} from 'angular2/http';
    import {Message} from '../models/message';
    import {Injectable} from 'angular2/core';
    import {Observable} from 'rxjs/Observable';
    import {AppSettings} from '../appSettings';
    import 'rxjs/add/operator/map';
    
    @Injectable()
    export class MessageService {
    
        constructor(private http: Http) { }
    
        getMessages(): Observable {
            return this.http.get(AppSettings.API_ENDPOINT+'/messages')
                .map(response => response.json())
                .map((messages: Object[]) => {
                    return messages.map(message => this.parseData(message));
                });
        }
    
        private parseData(data): Message {
            return new Message(data);
        }
    }
    

提交回复
热议问题