I have a simple method that at the end of it I want to redirect to another component:
export class AddDisplay{
display: any;
addPairTo(name: string, pairTo: string){
this.display = {};
this.display.name = name;
this.display.pairTo = pairTo;
}
}
What I wanna do is at the end of the method redirect to another component:
export class AddDisplay{
display: any;
addPairTo(name: string, pairTo: string){
this.display = {};
this.display.name = name;
this.display.pairTo = pairTo;
this.redirectTo('foo');
}
}
How do I achieve this in Angular 2?
first configure routing
import {RouteConfig, Router, ROUTER_DIRECTIVES} from 'angular2/router';
and
#RouteConfig([
{ path: '/addDisplay', component: AddDisplay, as: 'addDisplay' },
{ path: '/<secondComponent>', component: '<secondComponentName>', as: 'secondComponentAs' },
])
then in your component import and then inject Router
import {Router} from 'angular2/router'
export class AddDisplay {
constructor(private router: Router)
}
the last thing you have to do is to call
this.router.navigateByUrl('<pathDefinedInRouteConfig>');
or
this.router.navigate(['<aliasInRouteConfig>']);
#kit's answer is okay, but remember to add ROUTER_PROVIDERS to providers in the component. Then you can redirect to another page within ngOnInit method:
import {Component, OnInit} from 'angular2/core';
import {Router, ROUTER_PROVIDERS} from 'angular2/router'
#Component({
selector: 'loginForm',
templateUrl: 'login.html',
providers: [ROUTER_PROVIDERS]
})
export class LoginComponent implements OnInit {
constructor(private router: Router) { }
ngOnInit() {
this.router.navigate(['./SomewhereElse']);
}
}
This worked for me Angular cli 6.x:
import {Router} from '#angular/router';
constructor(private artistService: ArtistService, private router: Router) { }
selectRow(id: number): void{
this.router.navigate([`./artist-detail/${id}`]);
}
callLog(){
this.http.get('http://localhost:3000/getstudent/'+this.login.email+'/'+this.login.password)
.subscribe(data => {
this.getstud=data as string[];
if(this.getstud.length!==0) {
console.log(data)
this.route.navigate(['home']);// used for routing after importing Router
}
});
}
Related
I am trying to use angular routing to route to a new url when a button is clicked. I also need to use the module HttpClient to call some calls to the backend. However, whenever I create a HttpClient object, the routing doesn't work and it routes to a blank page with no url extension. When I delete the object, the routing works again. Anyone know how to overcome this? Here are some of my code snippets.
agent-page-component.ts (I create a Agent Service in the constructor)
import { Router} from "#angular/router";
import { Agent } from '../../models/agent.model'
import { AgentService } from '../../services/agent.service';
import { Subject, Subscription } from 'rxjs';
#Component({
selector: 'app-agent-page',
templateUrl: './agent-page.component.html',
styleUrls: ['./agent-page.component.css']
})
export class AgentPageComponent implements OnInit {
agents: Agent[] = [];
private agentSub: Subscription;
constructor(private agentService: AgentService){}
ngOnInit() {
this.agentService.getAgents();
this.agentSub = this.agentService.getAgentUpdateListener().subscribe((agents: Agent[]) => {
this.agents = agents;
});
}
ngOnDestroy() {
this.agentSub.unsubscribe();
}
}
agent.service.ts (this is where I import an HttpClient)
import { Injectable } from '#angular/core';
import { Subject } from 'rxjs';
import { HttpClient, HttpClientModule } from '#angular/common/http';
#Injectable({providedIn: 'root'})
export class AgentService {
private agents: Agent[] = [];
private agentsUpdated = new Subject<Agent[]>();
constructor(private http: HttpClient){}
getAgentUpdateListener() {
return this.agentsUpdated.asObservable();
}
getAgents(){
this.http.get<{message: string, agents: Agent[]}>('http://localhost:3000/agents/Breach').subscribe((agentList) => {
this.agents = agentList.agents;
})
}
}
app-routing.module.ts
import { Routes, RouterModule } from '#angular/router';
import { AgentPageComponent } from './components/agent-page/agent-page.component';
import { HomePageComponent } from './components/home-page/home-page.component';
const routes: Routes = [
{path: 'agents', component: AgentPageComponent},
{path: '', component: HomePageComponent}
];
#NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
export class AppRoutingModule { }
I am looking for ways of redirecting a page to the maintenance page in angular but i am new and am research different methods for turning on maintenance mode
i found a possible solution here: # the approved answer
Angular JS redirect to page within module config
however i don't know how to implement it
if there someone who could explain it, i would appreciate it greatly
using an authGuard will solve this problem
auth-guard.service.ts file:
import { Injectable } from '#angular/core';
import { CanActivate, Router, RouterStateSnapshot, ActivatedRouteSnapshot } from '#angular/router';
import { AuthService } from './auth.service';
import { Observable } from 'rxjs';
#Injectable()
export class AuthGuardMaintenance implements CanActivate {
constructor(
private authService: AuthService, private router: Router
) {}
canActivate(): Observable<boolean> | Promise<boolean> | boolean {
if (this.authService.inMaintenance()) {
alert('This Site Is Still Under Maintenance')
this.router.navigate(['/maintenance']);
return false;
} else {
this.router.navigate(['/']);
return true;
}
}
}
auth.service file:
import { Injectable } from '#angular/core';
#Injectable({
providedIn: 'root'
})
export class AuthService {
constructor() { }
inMaintenance() {
return false;
}
}
then import it in the app.module.ts file and add it to providers
then import the auth guard to the app-routing.module.ts file add the property
canActivate: [AuthGuardMaintenance]
to the the root route
eg
export const routes: Routes = [
{ path: '', component: MainComponent, canActivate: [AuthGuardMaintenance] },
{ path: 'maintenance', component: MaintenanceViewComponent },
{ path: '**', component: PageNotFoundComponent },
];
I am trying to extend some components with another class but I got
[Angular] Can't resolve all parameters for MyProjectsComponent in 'pathtomyproject'/src/app/my-projects/my-projects.component.ts: ([object Object], ?).
security.ts
import { Router} from '#angular/router';
export abstract class Security {
constructor(
protected router: Router
) { }
isLogged() {
if (!sessionStorage.getItem('user')) {
this.router.navigate(['/login']);
}
}
}
my-projects.component
import { Component, OnInit } from '#angular/core';
import { RouterModule, Router, ActivatedRoute } from '#angular/router';
import { ProjectService } from './project.service';
import { Security } from '../security';
#Component({
selector: 'app-my-projects',
templateUrl: './my-projects.component.html',
styleUrls: ['./my-projects.component.scss'],
providers: [ProjectService],
})
export class MyProjectsComponent extends Security implements OnInit {
projects: Array<any>;
constructor(
private projectService: ProjectService,
protected router
) {
super(router);
}
ngOnInit() {
this.getProjects();
}
async getProjects() {
const data: any = await this.projectService.getAll();
this.projects = data._embedded.projects;
}
delete(id) {
this.projectService.delete(id);
this.getProjects();
}
edit(id) {
const path = `/edit/${id}`;
this.router.navigate([path]);
}
}
There might be some issue in the constructor of the MyProjectsComponent. You misconfigured the dependency injection of the router. Change it to:
constructor(
private projectService: ProjectService,
protected router: Router // <-- DI for Router
) {
super(router);
}
and then it should work.
I tried to reproduce your issue in this stackblitz:
https://stackblitz.com/edit/angular-aifdew
I have created a shared service in order to store global information in my app:
import { Injectable } from '#angular/core';
import 'rxjs/add/operator/toPromise';
#Injectable()
export class SharedService {
GLOBAL_WIDTH = 300;
USER_PROFILE : any = {
}
}
Then, I declare it in appModule:
import { SharedService} from './shared.service';
#NgModule({
providers: [
SharedService,
],
bootstrap: [ AppComponent ]
})
export class AppModule { }
The next thing I want to do is to get/set data from this service.
I currently import SharedService to each component it is required, and using the constructor I get/set info:
import { SharedService } from './shared.service';
...
constructor(private sharedService : SharedService) {
this.sharedService.USER_PROFILE = profile;
});
});
}
And for using in another Component:
//Inside TopNav
import { SharedService } from '../shared.service';
export class TopNav implements OnInit{
userProfile = this.sharedService.USER_PROFILE;
constructor(
private router: Router,
private sharedService : SharedService) {
}
));
}
...
}
But this looks wrong to me, as if I understand correctly, I instantiate SharedService on every class I use it that way?
Also, will it be consistent?
I was using the googleplace directive for the Google places autocompletor.
It works when I use this directive in AppComponent as shown in the link but doesn't work when I used it in the child Components.
app.routes.ts
import { provideRouter, RouterConfig } from '#angular/router';
import { BaseComponent } from './components/base/base.component';
import { DashboardComponent } from './components/dashboard/dashboard.component';
const routes: RouterConfig=
[
{path:"",redirectTo:"/admin",pathMatch:'full'},
{path:"admin",component:BaseComponent,
children:[
{ path: '', component: BaseComponent},
{ path: 'dashboard', component: DashboardComponent},
]
}
];
export const appRouterProviders = [
provideRouter(routes)
];
main.ts
import {bootstrap} from '#angular/platform-browser-dynamic';
import {AppComponent} from './app.component';
import {appRouterProviders} from './app.routes';
bootstrap(AppComponent,[appRouterProviders]);
app.component.ts
import {Component} from '#angular/core';
import {ROUTER_DIRECTIVES} from '#angular/router';
#Component({
selector : 'my-app',
template: `
<router-outlet></router-outlet>
` ,
directives:[ROUTER_DIRECTIVES]
})
export class AppComponent {
}
base.component.ts
import {Component,OnInit} from '#angular/core';
import { provideRouter, RouterConfig,ROUTER_DIRECTIVES,Router } from '#angular/router';
#Component({
selector: 'app-base',
templateUrl:"../app/components/base/base.html",
directives:[ROUTER_DIRECTIVES],
precompile:[]
})
export class BaseComponent implements OnInit{
constructor(private _router:Router){}
ngOnInit():any{
this._router.navigate(["admin/dashboard"]);
}
}
base.html has <router-outlet></router-outlet> has its content
dashboard.component.ts
import {Component,OnInit} from '#angular/core';
import { provideRouter, RouterConfig,ROUTER_DIRECTIVES,Router } from '#angular/router';
import {GoogleplaceDirective} from './../../../directives/googleplace.directive';
#Component({
selector: 'dashboard',
template:`
<input type="text" [(ngModel)] = "address" (setAddress) = "getAddress($event)" googleplace/>
`,
directives:[ROUTER_DIRECTIVES,GoogleplaceDirective]
})
export class DashboardComponent implements OnInit{
constructor(private _router:Router){}
ngOnInit():any{
// this._router.navigate(["dashboard/business"]);
}
public address : Object;
getAddress(place:Object) {
this.address = place['formatted_address'];
var location = place['geometry']['location'];
var lat = location.lat();
var lng = location.lng();
console.log("Address Object", place);
}
}
googleplace.directive
import {Directive, ElementRef, EventEmitter, Output} from '#angular/core';
import {NgModel} from '#angular/common';
declare var google:any;
#Directive({
selector: '[googleplace]',
providers: [NgModel],
host: {
'(input)' : 'onInputChange()'
}
})
export class GoogleplaceDirective {
#Output() setAddress: EventEmitter<any> = new EventEmitter();
modelValue:any;
autocomplete:any;
private _el:HTMLElement;
constructor(el: ElementRef,private model:NgModel) {
this._el = el.nativeElement;
this.modelValue = this.model;
var input = this._el;
this.autocomplete = new google.maps.places.Autocomplete(input, {});
google.maps.event.addListener(this.autocomplete, 'place_changed', ()=> {
var place = this.autocomplete.getPlace();
this.invokeEvent(place);
});
}
invokeEvent(place:Object) {
this.setAddress.emit(place);
}
onInputChange() {
}
}
index.html
Output:
Update:
Found that, it works perfectly when there is one router-outlet tag
in the project, but fails to work when we have nested router-outlet as
above example has nested router-outlet
Github link here
Is there any issue with directive code with child components of a component?
Please let me know how I can resolve this issue.
The issue is https://maps.googleapis.com/maps/api/place/js/AutocompletionService.GetPredictions require an api key, when you use it inside a router child.
index.html
<script src="https://maps.googleapis.com/maps/api/js?key=API_KEY&libraries=places&sensor=false"></script>
Put your google API key in place of API_KEY.
I cannot explain the difference in behavior between child component(no api key needed) and router child(api key required).
According to Google Map Api documentation, API key is required:
https://developers.google.com/maps/documentation/javascript/places-autocomplete