dependency injection - angular 2 pass variable from injectable to component -
i wrote http interceptor in order catch 5xx errors server. idea in app.component.html have component (bad-response) must displayed if there 5xx error. in interceptor can check whether there error. how can pass information "bad-response" component?
i've tried create service, injected in component getting variable value , in interceptor setting it, no luck.
app.component.html
<top-nav></top-nav> <router-outlet></router-outlet> <bad-response></bad-response> //need pass info 5xx error here
interceptor.ts
@injectable() export class interceptedhttp extends http { constructor(backend: connectionbackend, defaultoptions: requestoptions) { super(backend, defaultoptions); } request(url: string | request, options?: requestoptionsargs): observable<response> { return super.request(url, options); } get(url: string, options?: requestoptionsargs): observable<response> { super.get(url, this.getrequestoptionargs(options)).subscribe((res: response) => { // here can response status code via res.status }); return super.get(url, this.getrequestoptionargs(options)); } ...other code }
bad-response.component.html
<div *ngif="isbadresponse"> sorry, there connection problems </div>
bad-response.component.ts
import {component, oninit} '@angular/core'; @component({ selector: 'bad-response', templateurl: './bad-response.component.html' }) export class badresponsecomponent implements oninit { isbadresponse: boolean; constructor() { } ngoninit() { } }
i suggest making badresponsecomponent
take input variable parent component , there on.
you can achieve using @input
decorator.
an example of badresponsecomponent
this:
import {component, oninit, input} '@angular/core'; @component({ selector: 'bad-response', templateurl: './bad-response.component.html' }) export class badresponsecomponent implements oninit { @input() isbadresponse: boolean; constructor() { } ngoninit() { } }
in case parent component using badresponsecomponent
provide isbadresponse
boolean , can afterwards.
component interaction - source learn more component interaction.
Comments
Post a Comment