import { Injectable } from '@angular/core' ; import { BehaviorSubject , Observable , of , Subscription } from 'rxjs' ; import { catchError , take , tap } from 'rxjs/operators' ; import { ApiResponse , ApiService } from '../../../../common/api/api.service' ; /**
 *  Tag object
 */ export type Tag = { selected : boolean ; value : string ; type : string ; } ; /**
 * Singleton service at lazy module level, dealing with tags for onboarding v3
 */ @ Injectable ( { providedIn : 'root' } ) export class OnboardingV3TagsService { /**
     * Holds selected tags
     */ private _tags$ : BehaviorSubject < Tag [ ] > = new BehaviorSubject < Tag [ ] > ( [ ] ) ; private subscriptions : Subscription [ ] = [ ] ; constructor ( private api ) { } ngOnDestroy ( ) { for ( let subscription of this . subscriptions ) { subscription . unsubscribe ( ) ; } } returns { BehaviorSubject < Tag [ ] > } get tags$ ( ) : BehaviorSubject < Tag [ ] > { return this . _tags$ ; } param { BehaviorSubject < Tag > } set tags$ ( tags$ ) { this . _tags$ = tags$ ; } returns { OnboardingV3TagsService } public loadTags ( ) { this . subscriptions . push ( this . api . get ( 'api/v2/hashtags/suggested' , { trending : 0 , defaults : 1 , limit : 15 , } , 3 ) . pipe ( take ( 1 ) , catchError ( ( e ) => { console . error ( e ) ; return of ( [ ] ) ; } ) ) . subscribe ( ( response ) => { this . tags$ . next ( response . tags ) ; } ) ) ; return this ; } param { string } tagValue return { Promise < OnboardingV3TagsService > } public async toggleTag ( tagValue ) { this . subscriptions . push ( this . tags$ . pipe ( take ( 1 ) , tap ( tags => { for ( let i = 0 ; i < tags . length ; i ++ ) { if ( tags [ i ] . value === tagValue ) { let requestObservable ; const endpoint = `api/v2/hashtags/user/${ tags [ i ] . value }` ; if ( ! tags [ i ] . selected ) { requestObservable = this . api . post ( endpoint ) ; } else { requestObservable = this . api . delete ( endpoint ) ; } tags [ i ] . selected = ! tags [ i ] . selected ; this . subscriptions . push ( requestObservable . pipe ( take ( 1 ) , catchError ( ( e ) => { console . error ( e ) ; return of ( null ) ; } ) ) . subscribe ( ) ) ; } } } ) ) . subscribe ( ) ) ; return this ; } }