0

I have a service defines that simply does the following:

@Injectable()
export class SettingService {

  settingsForm : FormGroup;

  constructor(private http:HttpClient, private httpErrorHandlerService : HttpErrorHandlerService) { }

    getPreference()   {
      return this.http.get<Preference>('/api/admin/config');
    }

Here is snippet of Preference Model

export class Preference {

 utilityName : string;
 utilitySupportUrl : string
 utilitySupportPhone : string;
 utilitySupportEmail : string;
 utilityPayBillUrl : string;
 utilityUrl : string;
 defaultLocale : string;

 showTOC : Boolean;
 showLastBilledDate : Boolean ;

 notificationRangeInHours : String;

In my component..

settingsForm: FormGroup;
  public utilityPreference: Preference = new Preference();

 constructor(private settingService: SettingService, private messageService: MessageService, private httpErrorHandler: HttpErrorHandlerService, private fb: FormBuilder, @Inject(APP_CONFIG) private config: IAppConfig) {
     this.settingService.getPreference().subscribe((data)  => { 
     console.log(data); 
     this.utilityPreference = data;
    });
console.log("====Component's preference:"+ JSON.stringify(this.utilityPreference));

My issue is my component is not able to get the copy of the Observable returned by the subscribe on my service. I was setting it as

this.utilityPreference = data;

In other words if i do this.utilityPreference.utilityName, i see NULL

Can someone point me in the right direction here ?

Radonirina Maminiaina
  • 6,958
  • 4
  • 33
  • 60
Jiji 007
  • 29
  • 1

1 Answers1

0

The problem that you are facing is that settingService.getPreference() is asynchronous. So your console.log evaluates first and then, some time later, getPreference() returns and subscribe block gets executed.

constructor(...) {
  this.settingService.getPreference().subscribe(data => { 
     this.utilityPreference = data;
     console.log('second', this.utilityPreference)
  });
  console.log('first', this.utilityPreference)
}

Also as others suggested, consider moving the logic to ngOnInit. Constructors should be thin, and only handle the dependency injection.

Tomasz Kula
  • 16,199
  • 2
  • 68
  • 79