Angular Access data from Service

前端 未结 3 506
猫巷女王i
猫巷女王i 2021-01-26 11:52

I\'m using angular 5 and httpclient. I\'m not a big fan of the built in environments to set up my environment api url\'s that I need to consume. I have switched to using an ngin

3条回答
  •  孤街浪徒
    2021-01-26 12:50

    You should be having the constant class as an @Injectable and have methods to set the value as below

    @Injectable()
    export class Constants {    
    
       api1 :string; // NEED API1 URL FROM SERVICE HERE;
    
       api2: string; // NEED API2 URL FROM SERVICE HERE
    
    
       setValueApi1(val){
           this.api1 = val;
       }
    }
    

    You can inject this to the constructor and call the method to set the value by passing the response as below

    @Injectable()
    export class ConfigurationService {
    private baseUrl = 'https://someUrl.com';
    
    constructor( private http: HttpClient,private constants:Constants ) {  }
    
        getConfig(): Observable { 
          return this.http
          .get(this.baseUrl + '/config')
          .map(res=>res)
        }
    }
    

    In your component you can subscribe to the response value and set the api value by calling the method as below

    this.getConfig().subscribe(response => {
        this.constants.setValueApi1(response))
    })
    

提交回复
热议问题