Search code examples
angularangular-http-interceptorsangular-httpclient

Cannot push data through a service via HttpInterceptor


I created a MessageService that I push data into which is then read by my app.main to display those messages to the user. When I use this service in a component it works fine. What I want to do is move that up to the HttpInterceptor level which will monitor all HttpResponse for server messages and push them into the service for user display.

Here is my service:

@Injectable()
export class MessageService {
  private successMessageList = new Subject<string>();
  successMessages$ = this.successMessageList.asObservable();

  constructor() { }

  addSuccessMsg(msg: string) {
    this.setMsgs(this.successMessageList, msg);
  }

  private setMsgs(privMsgArray: Subject<string>, newMsgs: any) {
    let messages = [];
    messages.push(newMsgs);

    messages.forEach(message => privMsgArray.next(message));
    console.log(this.successMessageList);
  }
}    

Here is my HttpInterceptor

@Injectable()
export class MyHttp implements HttpInterceptor {
  constructor(private messageService: MessageService) {}

  intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    return next.handle(req).do((event: HttpEvent<any>) => {
        if (event instanceof HttpResponse) {
          if(event.body['successMsg']) {
             this.messageService.addSuccessMsg(event.body['successMsg']);
          }
        }
      })
  }
}

This is my app.main which reads the data

export class AppComponent implements OnInit {
  successMessages = [];

  constructor(private messageService: MessageService) { }

  ngOnInit(): void {
    this.messageService.successMessages$.subscribe(
      message => {
        console.log(message);
        setTimeout(() => {
          this.successMessages.push(message);
        });
      });
  }
}

With some console statements I can see that data is getting into the messageService.setMsgs(...) private method correctly but it's never reaching my app.main like it does when I send messages via components. There are no error messages or anything, it just doesn't work.

One thing I did notice is in the MessageService.setMsgs(..) I put a console statement for successMessageList. When i add a message via a component I get an output that looks like this (NOTE the observers: Array(1) vs observers: Array(0) )

Subject {_isScalar: false, observers: Array(1), closed: false, isStopped: false, hasError: false, …}

But when I add a message via the HttpInterceptor I get this

Subject {_isScalar: false, observers: Array(0), closed: false, isStopped: false, hasError: false, …}

Any ideas on whats going on would be greatly appreciated!

I am using Angular 5


Solution

  • This issue was 100% user error. In my app.main component I was declaring the messageService as a provider in the @Component so the service was not a shared singleton like i was expecting it to be. After i removed that everything works as expected.