Angular 2 - Observable gets not recreated a second time

43 views
Skip to first unread message

Curtis Newton

unread,
Mar 3, 2017, 5:35:27 AM3/3/17
to Angular and AngularJS discussion
hello,

in my translation service when I set a new language, the observable is not recreated

I mean the code in the anonymous function gets not executed a second time

I tried many different things, but although the language json gets loaded on startup, it does not work after that

    @Injectable()
    export class TranslateService
    {
        private trads={};
        private language="en";
   
          public translationLoaded : Observable<boolean>;
   
          private translationLoadedObserver : Observer<boolean>;
   
        constructor(private http:Http,private cookieService:CookieService )
        {
            this.fetchTranslation();
        }
   
        fetchTranslation()
        {
            this.getLanguage();
   
            this.translationLoaded = Observable.create((observer :Observer<boolean>)=>
            {
                  this.translationLoadedObserver = observer;
   
                  this.http.get("app/translations/"+this.language+".json")
                .map(res => res.json())
                .subscribe(
                    res =>
                    {
                        this.trads = res;
                        this.translationLoadedObserver.next(true); //add true to the observable
                    },
                    error =>
                    {
                        console.log(error);
                    },
                );
            }).share();
        }
   
        getTranslation = function(text:string) : string
        {
            if(this.trads[text])
                return this.trads[text];
            else
                return "<<<"+text+">>>"
        };
   
        getLanguage()
        {
                this.language=this.cookieService.get("edenred_catalog_language");
            return this.language;
        }
   
        setLanguage(language:string)
        {
            this.language=language;
            this.cookieService.put("edenred_catalog_language",language);
            //this.translationLoadedObserver.next(false);
            //this.fetchTranslation();
            //window.location.reload();
        }
    }

regards

Sander Elias

unread,
Mar 3, 2017, 5:54:14 AM3/3/17
to Angular and AngularJS discussion
Hi Curtis,

this is inside your fetch:
 this.translationLoaded = Observable.create((observer :Observer<boolean>)=>

That means that you reassign your observable when you do a fetch. Probably you are breaking the reference. Move it out of your fetch, and just issue an next.

Regards
Sander

Message has been deleted

Curtis Newton

unread,
Mar 3, 2017, 9:44:38 AM3/3/17
to Angular and AngularJS discussion
man you just saved me, and it was so obvious after all, thanks
Reply all
Reply to author
Forward
0 new messages