How to return observable from subscribe
You can't return an observable from subscribe but if you use map
instead of subscribe
then an Observable
is returned.
canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot):Observable<boolean> {
// get route to be activated
this.routeToActivate = route.routeConfig.path;
// get user access levels
return this._firebase.isUserAdminObservable
.map(user => {
// do something here
// user.access_level;
return true;
})
.first(); // for the observable to complete on the first event (usually required for `canActivate`)
// first needs to be imported like `map`, ...
}
canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot):Observable<boolean> {
// get route to be activated
this.routeToActivate = route.routeConfig.path;
let subject = new Subject();
// get user access levels
this._firebase.isUserAdminObservable
.map(user => {
let accessLevel = user.access_level;
if (accessLevel === 'admin' ) {
subject.emit(true);
subject.complete();
}
return user;
});
return subject;
}
Couldn't we just use pipe
with map
from import { map } from 'rxjs/operators';
?
import { map } from 'rxjs/operators';
@Injectable({
providedIn: 'root'
})
export class SearchHostService {
constructor(private readonly http: HttpClient) {}
searchForHosts(searchString: string): Observable<Employee[]> {
return this.http
.get<Employee[]>('./assets/host-users.json')
.pipe(
map(employees =>
employees.filter(({ displayName }) =>
displayName.toLowerCase().startsWith(searchString),
),
),
);
}
}
Do this if you want to subscribe to observable, process the result and then return the same result in subscribe:
function xyx(): Observable<any> {
const response = someFunctionThatReturnsObservable().pipe(map(result => {
// here do any processing of the result //
return result; // return back same result.
}
))
return response;
}