I have a service with a property in it that I want to refer to and change in multiple components. Can I just reference it directly in my components by assigning it to a property in the component or should I subscribe to an observable? I tried it both ways and when I modify it in the component both ways seem to change the property in the service.
account.service.ts
export class AccountService {
constructor(private http: HttpClient) { }
testAccount: Account = {
domain_name: "fortestaccoutnpage2",
account_number: "fortestaccoutnpage2",
bill_timing: "anniversary",
}
getAccount(): Observable<Account> {
return of(this.testAccount);
}
}
account.component.ts
export class AccountComponent implements OnInit {
constructor(private _accountService: AccountService) { }
changeAccountNumber() {
this.account.account_number = "changed"
}
account: Account = this._accountService.testAccount;
grabAccount(): void {
this._accountService.getAccount()
.subscribe(account => this.account = account);
}
ngOnInit() {
//this.grabAccount();
}
}
Is the above example I basically have account
in the component refer to the testAccount
in the service and the changeAccountNumber
method works. I commented out the method to have account
subscribe to the observable, but when I do it that way it works as well. Is one way better than the other or are both fine?