Please read this post which covers the fundamental issue you’re having here and introduces the watch/peek/poke idiom I like to deploy in situations like this. You do not want to be manually instantiating Promise
s, read this for more on HttpParams
which are a safer and more readable way to deal with query strings than what you currently have.
export interface Customer {
id: string;
last_name: string;
first_name: string;
email: string;
}
import {isString, isObjectLike} from "lodash-es";
class CustomerService {
private customer$ = new BehaviorSubject<Customer | undefined>(undefined);
private apiParams = new HttpParams();
constructor(private http: Http, private storage: Storage) {
this.storage.ready()
.then(() => this.storage.get("custid"))
.then(cust => this.customer$.next(cust));
this.apiParams = this.apiParams.set("consumer_key", WHATEVER_GOES_HERE);
this.apiParams = this.apiParams.set("consumer_secret", MORE_WHATEVER);
}
private customerUrl(custid: string): string {
return `${SITE_URL}${WOOCOMMERCE_PATH}customers/${id}`;
}
peekCustomer(): Customer | undefined {
return this.customer$.value;
}
watchCustomer(): Observable<Customer | undefined> {
return this.customer$;
}
pokeCustomer(cust: Customer | string | undefined): Observable<Customer | undefined> {
if (isString(cust)) {
// retargeting new customer id
this.storage.set("custid", cust);
return this.http.get(this.customerUrl(cust), {params: this.apiParams})
.pipe(tap(custo => this.customer$.next(custo));
} else if (isObjectLike(cust)) {
// updating existing customer
return this.http.put(this.customerUrl(cust.id), cust, {params: this.apiParams})
.pipe(map(() => cust), tap((custo) => this.customer$.next(custo));
} else {
// clearing
this.storage.remove("custid");
this.customer$.next(undefined);
return of(undefined);
}
}
}