import {Injectable} from '@angular/core'; import {Http} from '@angular/http'; import {HttpClient} from "@angular/common/http"; import {CommunityInfo} from '../community/communityInfo'; import {EnvProperties} from '../../utils/properties/env-properties'; import {BehaviorSubject, Observable} from "rxjs"; import {map} from "rxjs/operators"; @Injectable() export class CommunitiesService { public communities: BehaviorSubject = null; constructor(private http: HttpClient) { this.communities = new BehaviorSubject([]); } updateCommunities(properties: EnvProperties, url: string) { this.getCommunities(properties, url).subscribe(res => { this.communities.next(res); }) } getCommunitiesState() { return this.communities.asObservable(); } getCommunities(properties: EnvProperties, url: string) { return this.http.get((properties.useCache) ? (properties.cacheUrl + encodeURIComponent(url)) : url) //.map(res => res.json()) .pipe(map(res => this.parseCommunities(res))); } parseCommunities(data: any): CommunityInfo[] { const communities: CommunityInfo[] = []; const length = Array.isArray(data) ? data.length : 1; for (let i = 0; i < length; i++) { const resData = Array.isArray(data) ? data[i] : data; const result: CommunityInfo = new CommunityInfo(); result['title'] = resData.name; result['shortTitle'] = resData.shortName; result['communityId'] = resData.id; result['queryId'] = resData.queryId; result['logoUrl'] = resData.logoUrl; result['description'] = resData.description; result['date'] = resData.creationDate; result['status'] = 'all'; if (resData.hasOwnProperty('status')) { result['status'] = resData.status; const status = ['all', 'hidden', 'manager']; if (status.indexOf(result['status']) === -1) { result['status'] = 'hidden'; } } if (resData.type != null) { result['type'] = resData.type; } if (resData.managers != null) { if (result['managers'] === undefined) { result['managers'] = new Array(); } const managers = resData.managers; const lengthManagers = Array.isArray(managers) ? managers.length : 1; for (let j = 0; j < lengthManagers; j++) { const manager = Array.isArray(managers) ? managers[j] : managers; result.managers[j] = manager; } } if (resData.subjects != null) { if (result['subjects'] === undefined) { result['subjects'] = new Array(); } const subjects = resData.subjects; const lengthSubjects = Array.isArray(subjects) ? subjects.length : 1; for (let j = 0; j < lengthSubjects; j++) { const subject = Array.isArray(subjects) ? subjects[i] : subjects; result.subjects[j] = subject; } } if (result['type'] === 'community' || result['type'] === 'ri') { communities.push(result); } } return communities; } }