Created
April 10, 2017 18:06
-
-
Save isaacplmann/5dd1cffd9f97200f5ae5b7315a14de27 to your computer and use it in GitHub Desktop.
Data Directive Implementation
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@Directive({ | |
exportAs: 'nqConnect', | |
selector: '[nqConnect]', | |
}) | |
export class ConnectRequestDirective implements OnInit, OnDestroy { | |
// tslint:disable-next-line:no-input-rename | |
@Input('nqConnect') | |
config: any = <ConnectRequestParams>undefined; | |
@Output() response: EventEmitter<any> = new EventEmitter(); | |
subscription: Subscription; | |
constructor( | |
// You could replace ConnectService with Http | |
private connectService: ConnectService, | |
@Optional() public host: NqConnectedComponent | |
) {} | |
ngOnInit(): void { | |
// Automatically get the latest data when the component loads | |
this.subscribe(this.config); | |
if (this.host) { | |
// Refresh data when the host component forces a refresh | |
this.host.nqRefresh.subscribe(() => this.forceRequest()); | |
} | |
} | |
ngOnDestroy(): void { | |
this.unsubscribe(); | |
} | |
subscribe(config: ConnectRequestParams): void { | |
this.unsubscribe(); | |
this.subscription = this.connectService.requestAsync(config) // or this.http.get(...) | |
.subscribe(response => { | |
if (this.response) { | |
// bind the received response to the host component | |
if (this.host) { | |
this.host.nqData = response; | |
} | |
// emit the response data | |
this.response.emit(response); | |
} | |
}); | |
} | |
unsubscribe(): void { | |
if (this.subscription) { | |
this.subscription.unsubscribe(); | |
} | |
} | |
forceRequest(): void { | |
this.subscribe(Object.assign({}, this.config, { force: true })); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment