I thought it would be the same way to inject Location just like how I inject Http. However my app breaks - the page does not render, if I uncomment "public location: Location" in the last line. As far as I can see, I have the correct import and providers array:
import {Component} from 'angular2/core';
import {
ROUTER_DIRECTIVES,
ROUTER_PROVIDERS,
RouteConfig,
Location,
LocationStrategy,
HashLocationStrategy
} from 'angular2/router';
import {TaskForm} from './task_form';
import {TaskList} from './task_list';
import {AboutUs} from './about_us';
@Component({
selector: 'task-app',
templateUrl: 'app/task_app.html',
providers: [ROUTER_PROVIDERS],
directives: [TaskForm, TaskList, ROUTER_DIRECTIVES]
})
@RouteConfig([
{path: '/', component: TaskApp, as: 'Home'},
{path: '/about_us', component: AboutUs, as: 'aboutUs'}
])
export class TaskApp {
constructor(/*public location: Location*/) {
In my index.html, I have the following line:
<script src="https://code.angularjs.org/2.0.0-beta.0/router.dev.js"></script>
In my bootstrap code, I have:
import {bootstrap} from 'angular2/platform/browser';
import {HTTP_PROVIDERS} from 'angular2/http';
import {provide} from 'angular2/core';
import {
ROUTER_DIRECTIVES,
ROUTER_PROVIDERS,
RouteConfig,
Location,
LocationStrategy,
HashLocationStrategy
} from 'angular2/router';
import {TaskApp} from './task_app';
import {MyService} from './my_service'
bootstrap(TaskApp, [HTTP_PROVIDERS, ROUTER_PROVIDERS, MyService, provide(LocationStrategy, {useClass: HashLocationStrategy})]);
Not sure whether I missed something or the current build is broken. If it is the first case, what did I miss?
Location is a service available in Angular 2+ apps that makes it easy to interact with the current URL path. For most navigation needs, the Angular router is the correct solution, but in a few cases the location service is needed to affect the url without involving the router.
@Inject() is a manual mechanism for letting Angular know that a parameter must be injected. It can be used like so: import { Component, Inject } from '@angular/core'; import { ChatWidget } from '../components/chat-widget';
Window Location Href href property returns the URL of the current page.
Dependency injection, or DI, is one of the fundamental concepts in Angular. DI is wired into the Angular framework and allows classes with Angular decorators, such as Components, Directives, Pipes, and Injectables, to configure dependencies that they need.
in your NgModule
providers: [
{ provide: 'locationObject', useValue: location}
]
in your component you need to Inject it so
import { Component, Inject } from '@angular/core';
constructor(
@Inject('locationObject') private locationObject: Location
) {}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With