To display data on the home page from a REST API using Interceptor in Angular 6, authorization with 'username' and 'password' is required. Previously, I successfully fetched data using Node.js. However, after switching to the Interceptor, an error occurred:
ERROR TypeError: You provided 'undefined' where a stream was expected. You can provide an Observable, Promise, Array, or Iterable.
at subscribeTo (subscribeTo.js:41)
at subscribeToResult (subscribeToResult.js:6)
at MergeMapSubscriber.push../node_modules/rxjs/_esm5/internal/operators/mergeMap.js.MergeMapSubscriber._innerSub (mergeMap.js:70)
at MergeMapSubscriber.push../node_modules/rxjs/_esm5/internal/operators/mergeMap.js.MergeMapSubscriber._tryNext (mergeMap.js:67)
at MergeMapSubscriber.push../node_modules/rxjs/_esm5/internal/operators/mergeMap.js.MergeMapSubscriber._next (mergeMap.js:50)
at MergeMapSubscriber.push../node_modules/rxjs/_esm5/internal/Subscriber.js.Subscriber.next (Subscriber.js:54)
at Observable._subscribe (scalar.js:5)
at Observable.push../node_modules/rxjs/_esm5/internal/Observable.js.Observable._trySubscribe (Observable.js:42)
at Observable.push../node_modules/rxjs/_esm5/internal/Observable.js.Observable.subscribe (Observable.js:28)
at MergeMapOperator.push../node_modules/rxjs/_esm5/internal/operators/mergeMap.js.MergeMapOperator.call (mergeMap.js:28)
The landing component function I created is as follows:
const userData = { username: 'anonymous', password: '' };
this.http
.post(`${this.baseURL}/auth/jwt/authenticate`, userData)
.subscribe(res => {
// console.log(res);
const token = JSON.parse(res['_body']).token;
this.publicToken = token;
if (token) {
this.publicTokenStatusListener.next(true);
localStorage.setItem('public-token', token);
}
});
The Interceptor code snippet is shown below:
intercept(
req: HttpRequest<any>,
next: HttpHandler
): Observable<HttpEvent<any>> {
const authToken = localStorage.getItem('public-token');
const copiedReq = req.clone({
params: req.params.set('auth', authToken)
});
return next.handle(copiedReq);
}
Although I'm returning the GET request for REST data from the service to fetch the observable, it's not functioning as expected.
I can retrieve the 'token' in the Interceptor. Any suggestions would be greatly appreciated.
Thank you in advance.