AngularJS Provider in TypeScript

Friday, October 24, 2014 by Rainer Stropek

AngularJS samples written in TypeScript are not that common on the internet. I get frequently asked how to write an AngularJS provider in TypeScript. Here is a "Hello World" sample.

// Interface describing the members that the provider's service offers
interface IGreetingService {
	getGreeting(): string;
}

// The following class represents the provider
class GreetingService implements ng.IServiceProvider {
	private greeting = "Hello World!";

	// Configuration function
	public setGreeting(greeting: string) {
		this.greeting = greeting;
	}

	// Provider's factory function
	public $get() : IGreetingService {
		return {
			getGreeting: () => { return this.greeting; }
		};
	}
}

// Define a controller depending our provider
class ControllerNeedingProvider {
	constructor($scope, GreetingService: IGreetingService) {
		$scope.Greeting = GreetingService.getGreeting();
	}
}

angular.module("ProviderApp", [])
	// Define provider
	.provider("GreetingService", GreetingService)
	// Configure provider (note the suffix "Provider" here)
	.config((GreetingServiceProvider: GreetingService) => {
		GreetingServiceProvider.setGreeting("Hello Provider");
	})
	.controller("ControllerNeedingProvider", ControllerNeedingProvider);
comments powered by Disqus

Rainer Stropek

Rainer Stropek

Co-founder, architect, developer

Bio

I am co-founder and CEO of the company software architects and have been serving this role since 2008. At software architects my team and I are developing the award-winning SaaS solution time cockpit. Previously, I founded and led IT consulting firms that worked in the area of developing software solutions based on the Microsoft technology stack.

In my work I focus on .NET development and software architecture. I have written some books and articles on C#, database development, Windows Azure, Windows 8 development, WPF, and Silverlight. Regularly I speak at conferences, do workshops and conduct trainings in Europe and the US. Since 2010 I have been MVP for Windows Azure.

I graduated the Higher Technical School Leonding (AT) for MIS with honors and hold a BSc (Hons) Computer Studies of the University of Derby (UK).

Contact

Twitter: @rstropek
Facebook
Google+
Xing
LinkedIn

Authors