Angular 2 – communication of typescript functions with external js libraries

Just fire a custom event using dispatchEvent. In Angular you can listen by adding to any component that is actually added to the DOM: in any template: <div (window:custom-event)=”updateNodes($event)”> or in the components class: @HostListener(‘window:custom-event’, [‘$event’]) updateNodes(event) { … } or in the @Component() or @Directive() annotation: @Component({ selector: ‘…’, host: {‘(window:custom-event)’:’updateNodes($event)’} }) where custom-event … Read more

How to avoid imports with very long relative paths in Angular 2?

TypeScript 2.0+ In TypeScript 2.0 you can add a baseUrl property in tsconfig.json: { “compilerOptions”: { “baseUrl”: “.” // etc… }, // etc… } Then you can import everything as if you were in the base directory: import {XyService} from “services/validation/xy.service”; On top of this, you could add a paths property, which allows you to … Read more

How can I watch for changes to localStorage in Angular2?

The key thing is to use window.addEventListener(“storage”, . While the library probably does it the “right” way for angular, here is a “light” version I put together, using .bind(this) instead of mucking about in angular’s internals. import { Injectable, OnDestroy } from ‘@angular/core’; import { Subject } from ‘rxjs/Subject’; import { share } from ‘rxjs/operators’; … Read more

Angular2: How to load data before rendering the component?

update If you use the router you can use lifecycle hooks or resolvers to delay navigation until the data arrived. https://angular.io/guide/router#milestone-5-route-guards To load data before the initial rendering of the root component APP_INITIALIZER can be used How to pass parameters rendered from backend to angular2 bootstrap method original When console.log(this.ev) is executed after this.fetchEvent();, this … Read more

What is the correct way to share the result of an Angular Http network call in RxJs 5?

EDIT: as of 2021, the proper way is to use the shareReplay operator natively proposed by RxJs. See more details in below answers. Cache the data and if available cached, return this otherwise make the HTTP request. import {Injectable} from ‘@angular/core’; import {Http, Headers} from ‘@angular/http’; import {Observable} from ‘rxjs/Observable’; import ‘rxjs/add/observable/of’; //proper way to … Read more