I am new to observables and I'm having trouble understanding how to use them properly.
Say I have this service:
class MyService {
query() {
return from(myApiCall()).pipe(
pluck('data'),
mergeMap(apiResponse => {
const obj = apiResponse.foo.map(el => {
return {
bar: el.bar,
otherProp: el.baz,
// how do I get the litteral value here and not an observable?
builtProp: this.buildProp(el.myProp)
}
})
return obj
)
}
buildProp(value) {
if(!value) {
return throwError('value missing')
}
return of(`the value is: ${value}`)
}
}
buildProp
is a public method that I'd like to have the option to call from elsewhere outside the MyService
class. There is nothing async about what it does, so it might as well return the value straightaway rather than an observable. But that might be inconsistent and annoying to use if some methods of MyService
return observables and others don't.
I thought of having a private method that returns the plain string to use when building the object, and another public method that returns of(buildProp(val))
, but that feels clunky (nevermind the difficulty of finding good names for these two separate methods now).
Should any public method on an Angular service always return an observable, even if there is nothing async about what that method does?
And in that particular case, how do I get the literal string rather than an observable for builtProp
in the returned object in an elegant and idiomatic Angular way?
builtProp: String(el.myProp)
give you back the string value directly? - Nicholas Kvar rxjs = require("rxjs") const value$ = rxjs.of('hello') const value = String(value$) console.log({value}) // => "[object Object]"
- PierreString(...)
instantiates a new string. Turning objects into strings usually results in the very unhelpful"[object Object]"
. And it is an object because that's what the unsubscribed observable is. - PierrebuildProp
. - Pierre