support-multiple-ric-instances
[portal/ric-dashboard.git] / webapp-frontend / src / app / services / instance-selector / instance-selector.service.ts
1 /*-
2  * ========================LICENSE_START=================================
3  * O-RAN-SC
4  * %%
5  * Copyright (C) 2019 AT&T Intellectual Property
6  * %%
7  * Licensed under the Apache License, Version 2.0 (the "License");
8  * you may not use this file except in compliance with the License.
9  * You may obtain a copy of the License at
10  *
11  *      http://www.apache.org/licenses/LICENSE-2.0
12  *
13  * Unless required by applicable law or agreed to in writing, software
14  * distributed under the License is distributed on an "AS IS" BASIS,
15  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16  * See the License for the specific language governing permissions and
17  * limitations under the License.
18  * ========================LICENSE_END===================================
19  */
20
21 import { HttpClient } from '@angular/common/http';
22 import { Injectable } from '@angular/core';
23 import { BehaviorSubject, Observable } from 'rxjs';
24 import { shareReplay, tap } from 'rxjs/operators';
25 import { RicInstance } from '../../interfaces/dashboard.types';
26
27 @Injectable({
28   providedIn: 'root'
29 })
30 export class InstanceSelectorService {
31   private selectedInstanceKey: BehaviorSubject<string> = new BehaviorSubject<string>('');
32   private instanceArray: Observable<RicInstance[]>;
33   private basePath = 'api/admin/instance';
34
35   constructor(private httpClient: HttpClient) { }
36
37   getInstanceArray(): Observable<RicInstance[]> {
38     if (this.instanceArray) {
39       return this.instanceArray;
40     }
41     return this.instanceArray = this.httpClient.get<RicInstance[]>(this.basePath)
42       .pipe(
43         tap(ricInstanceArray => {
44           this.initselectedInstanceKey(ricInstanceArray[0].key);
45         }),
46         shareReplay(1)
47       );
48   }
49
50   private initselectedInstanceKey(instanceKey: string) {
51     if (!this.selectedInstanceKey.value) {
52       this.selectedInstanceKey.next(instanceKey)
53     }
54   }
55
56   // This method may return the BehaviorSubject with empty string
57   // Afther subscribe that BehaviorSubject
58   // Please make sure this BehaviorSubject has non empty value
59   getSelectedInstancekey(): BehaviorSubject<string> {
60     return this.selectedInstanceKey;
61   }
62
63   updateSelectedInstance(instanceKey: string) {
64     this.selectedInstanceKey.next(instanceKey)
65   }
66
67 }