How to direct to another component page angular 5 - javascript

I have trouble to direct an angular page to another component which i created. It should be directed to 'belize-local-time-component' when I click "take me back". But for right now, when I click "take me back", it directed to 'belize-local-time-component'page, but it did not stay, instead of coming back to the current page. Please help!! Thank you.
welcome-component.component.html
<p>
This is what I'm all about. <strong>Take me back</strong>.
</p>
welcome-component.component.ts
import { Component, OnInit } from '#angular/core';
import { ActivatedRoute } from '#angular/router';
import { Router } from '#angular/router';
#Component({
selector: 'app-welcome-component',
templateUrl: './welcome-component.component.html',
styleUrls: ['./welcome-component.component.css']
})
export class WelcomeComponentComponent implements OnInit {
constructor(private route: ActivatedRoute,private router: Router) {
this.route.params.subscribe(res => console.log(res.id));
}
ngOnInit() {
}
sendMeHome() {
this.router.navigate(['./belize-local-time-component']);
}
}
app.module.ts
import { BrowserModule } from '#angular/platform-browser';
import { NgModule } from '#angular/core';
import { AppComponent } from './app.component';
import { WelcomeComponentComponent } from './welcome-component/welcome-component.component';
import { BelizeLocalTimeComponentComponent } from './belize-local-time-component/belize-local-time-component.component';
import { AppRoutingModule } from './/app-routing.module';
import { FormsModule } from '#angular/forms';
import { Routes, RouterModule } from '#angular/router';
#NgModule({
declarations: [
AppComponent,
WelcomeComponentComponent,
BelizeLocalTimeComponentComponent,
],
imports: [
BrowserModule,
AppRoutingModule,
FormsModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
app-routing.module.ts
import { NgModule } from '#angular/core';
import { CommonModule } from '#angular/common';
import { WelcomeComponentComponent} from './welcome-component/welcome-component.component';
import { BelizeLocalTimeComponentComponent } from './belize-local-time-component/belize-local-time-component.component';
import { Route } from '#angular/compiler/src/core';
import { Routes, RouterModule } from '#angular/router';
const routes: Routes = [
{
path: '',
component: WelcomeComponentComponent
},
{
path: 'belize-local-time-component',
component: BelizeLocalTimeComponentComponent
}
];
#NgModule({
imports:[RouterModule.forRoot(routes)],
exports:[RouterModule]
})
export class AppRoutingModule { }

The problem is with your anchor tag in Welcome component. You should remove href="" or use a button instead. Please check this sample that I have created for you:
https://stackblitz.com/edit/angular-yarabq

Swap the order of the paths in your routes.

Related

angular route is not working and not changing current view

I created a new component with 'ng generate component', but after pressing navigating the url the target view doesn't load, I don't know why. The url will be changed correctly but the view will be not changed.
export class AppComponent {
title = 'Overview';
constructor(private router: Router) { }
onPressStart($event){
this.router.navigate(['/start']);
}
}
app.module.ts:
import { BrowserModule } from '#angular/platform-browser';
import { NgModule } from '#angular/core';
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { StartComponent } from './start/start.component';
#NgModule({
declarations: [
AppComponent,
StartComponent
],
imports: [
BrowserModule,
AppRoutingModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
app-routing.mdoules.ts:
import { NgModule } from '#angular/core';
import { Routes, RouterModule } from '#angular/router';
import { StartComponent } from './start/start.component';
import {AppComponent} from './app.component';
const routes: Routes = [ {path: "", component:AppComponent}, {path: "start", component: StartComponent} ];
#NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
export class AppRoutingModule { }
The AppComponent and StartComponent should not be siblings like you did.
AppComponent is bootstrapped, that means it's your root component and you should not try to load it with a route.
So just put a <router-outlet></router-outlet> inside AppComponent which will act as a placeholder for route-loaded components.
Then remove AppComponent from the routes, and all of your routes will work.

Angular Firebase authentication always redirects to home page

In this Angular project which I am practicing through a tutorial,when I try to access pages that require authentication, I am redirected to login page and even the URL changes to http://localhost:4200/login?returnURL=%2Fcheck-out.
But after logging in ,it always redirects to home page irrespective of the links.
app.component.ts:
import { Component } from '#angular/core';
import { AuthService } from './auth.service';
import { Router } from '../../node_modules/#angular/router';
#Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
constructor(private auth:AuthService, router:Router){
auth.user$.subscribe(user=>{
if(user){
let returnUrl=localStorage.getItem('returnUrl');
router.navigateByUrl(returnUrl);
}
});
}
}
auth.service.ts:
import { Injectable } from '#angular/core';
import { AngularFireAuth } from '../../node_modules/angularfire2/auth';
import { Observable } from '../../node_modules/rxjs';
import * as firebase from 'firebase';
import { ActivatedRoute } from '../../node_modules/#angular/router';
#Injectable({
providedIn: 'root'
})
export class AuthService {
user$: Observable<firebase.User>;
constructor(private afAuth:AngularFireAuth,private route:ActivatedRoute) {
this.user$=afAuth.authState;
}
login(){
let returnUrl=this.route.snapshot.queryParamMap.get('returnUrl') ||'/';
localStorage.setItem('returnUrl',returnUrl);
this.afAuth.auth.signInWithRedirect(new firebase.auth.GoogleAuthProvider());
}
logout(){
this.afAuth.auth.signOut();
}
}
app.module.ts:
import { BrowserModule } from '#angular/platform-browser';
import { NgModule } from '#angular/core';
import {AngularFireModule} from 'angularfire2';
import {AngularFireDatabaseModule} from 'angularfire2/database';
import {AngularFireAuthModule, AngularFireAuth} from 'angularfire2/auth';
import { Observable} from 'rxjs';
import {RouterModule, RouterOutlet, Routes} from '#angular/router';
import { AppComponent } from './app.component';
import { environment } from '../environments/environment';
import { BsNavbarComponent } from './bs-navbar/bs-navbar.component';
import { HomeComponent } from './home/home.component';
import { ProductsComponent } from './products/products.component';
import { ShoppingCartComponent } from './shopping-cart/shopping-cart.component';
import { CheckOutComponent } from './check-out/check-out.component';
import { OrderSucessfulComponent } from './order-sucessful/order-sucessful.component';
import { MyOrdersComponent } from './my-orders/my-orders.component';
import { AdminProductsComponent } from './admin/admin-products/admin-products.component';
import { AdminOrdersComponent } from './admin/admin-orders/admin-orders.component';
import { LoginComponent } from './login/login.component';
import {NgbModule} from '#ng-bootstrap/ng-bootstrap';
import { AuthService } from './auth.service';
import { AuthGuard } from './auth-guard.service';
export const appRoutes: Routes = [
{path:'',component:HomeComponent},
{path:'products',component:ProductsComponent},
{path:'shopping-cart',component:ShoppingCartComponent},
{path:'login',component:LoginComponent},
{path:'check-out',component:CheckOutComponent,canActivate:[AuthGuard]},
{path:'order-sucessful',component:OrderSucessfulComponent,canActivate:[AuthGuard]},
{path:'my/orders',component:MyOrdersComponent,canActivate:[AuthGuard]},
{path:'admin/products',component:AdminProductsComponent,canActivate:[AuthGuard]},
{path:'admin/orders',component:AdminOrdersComponent,canActivate:[AuthGuard]}
]
#NgModule({
declarations: [
AppComponent,
BsNavbarComponent,
HomeComponent,
ProductsComponent,
ShoppingCartComponent,
CheckOutComponent,
OrderSucessfulComponent,
MyOrdersComponent,
AdminProductsComponent,
AdminOrdersComponent,
LoginComponent
],
imports: [
BrowserModule,
RouterModule.forRoot(appRoutes),
AngularFireModule.initializeApp(environment.firebase),
AngularFireDatabaseModule,
AngularFireDatabaseModule,
NgbModule.forRoot()
],
providers: [AngularFireAuth,AuthService,AuthGuard],
bootstrap: [AppComponent]
})
export class AppModule { }
Seems to be in your localStorage.getItem('returnUrl'); always set to root of the application better to first check if there is a value and then remove that value and redirect the user like below:
let returnUrl = localStorage.getItem('returnUrl');
if (returnUrl) {
localStorage.removeItem('returnUrl');
router.navigateByUrl(returnUrl);
}
Hope this will helps you!

Router navigate not loading component the first time

I'm having an issue with my Angular2/Meteor application.
I'm trying to redirect to a component from an other but it doesn't seem to load the first time. However, when I refresh the page, it loads perfectly.
When I debug, I see my html view without any of the variables displaying, my variables have values that seems correct, but they doesn't show on the View.
This is my Guard:
import { CanActivate } from "#angular/router";
import { Meteor } from 'meteor/meteor';
import { Router } from '#angular/router';
import { Injectable } from '#angular/core';
#Injectable()
export class RouteGuardService implements CanActivate {
constructor(public router: Router) { }
canActivate() {
if (Meteor.userId() != undefined) {
return true;
}
else {
let link = ['accueil'];
this.router.navigate(link);
return false;
}
}
}
My route.module :
import { Route } from '#angular/router';
import {AccueilComponent} from "./pages/accueil/accueil.component";
import {ChannelsComponent} from "./pages/channel/channels.component";
import { RouteGuardService } from './services/routeGuard.service';
export const routes: Route[] = [
{ path: '', component: AccueilComponent },
{ path: 'accueil', component: AccueilComponent, pathMatch: 'full' },
{ path: 'channel', component: ChannelsComponent, canActivate: [RouteGuardService], pathMatch: 'full'},
];
I hope I was clear with my explanation. Do not hesitate to ask more information.
Thanks !
EDIT:
My app.module:
import { NgModule } from '#angular/core';
import { BrowserModule } from '#angular/platform-browser';
import { FormsModule, ReactiveFormsModule } from '#angular/forms';
import { RouterModule } from '#angular/router';
import { Ng2DragDropModule } from 'ng2-drag-drop';
import { AccountsModule } from 'angular2-meteor-accounts-ui';
import { AppComponent } from './app.component';
import { MomentModule } from "angular2-moment";
import { ModalModule } from 'ngx-modialog';
import { BootstrapModalModule } from 'ngx-modialog/plugins/bootstrap';
import { ChannelModal } from './pages/channel/channel_search/channel-list.modal';
import { RouteGuardService } from './services/routeGuard.service';
import { AccueilComponent } from "./pages/accueil/accueil.component";
import { LOGIN_DECLARATIONS } from './pages/login';
import { CHANNEL_DECLARATIONS } from './pages/channel';
import { routes } from './app.routes';
#NgModule({
imports: [
RouterModule.forRoot(routes),
Ng2DragDropModule.forRoot(),
ModalModule.forRoot(),
BrowserModule,
AccountsModule,
FormsModule,
ReactiveFormsModule,
MomentModule,
BootstrapModalModule,
],
declarations: [
AppComponent,
AccueilComponent,
...LOGIN_DECLARATIONS,
...CHANNEL_DECLARATIONS,
ChannelModal
],
bootstrap: [
AppComponent
],
entryComponents: [
ChannelModal
],
providers:[
RouteGuardService
]
})
export class AppModule { }
Alright I found an answer. I don't know if it's the best solution, but at least it's working.
this.zone.run(() => this.router.navigate(['channel']));
This solve my problem.

How to embed twitter timeline to Angular4 app

New to Angular, please bear with me. I need to load in tweets from a specific timeline. What is the best way to accomplish this? I've tried using this package (https://www.npmjs.com/package/ng4-twitter-timeline), and have followed the instructions in that documentation, but I still get the error that "ng4-twitter-timeline is not a known element."
I've also tried adding in
<script src="https://platform.twitter.com/widgets.js" async></script>
to index.html...
Are there additional scripts that need to be loaded in for this to work?
app.module.ts
...
import { BrowserModule } from '#angular/platform-browser';
import { NgModule } from '#angular/core';
import { AppRoutingModule } from './app-routing.module';
import { RouterModule } from '#angular/router';
import { SwiperModule } from 'angular2-useful-swiper';
import { AngularFontAwesomeModule } from 'angular-font-awesome/angular-font-awesome';
import { FormsModule } from '#angular/forms';
import { HttpModule } from '#angular/http';
import { ShareModule } from 'ng2share/share.module';
import { MasonryModule } from 'angular2-masonry';
import { routes } from './app-routing.module';
import { Ng4TwitterTimelineModule } from 'ng4-twitter-timeline/lib/index';
#NgModule({
declarations: [
...
],
imports: [
BrowserModule,
AppRoutingModule,
HttpModule,
AngularFontAwesomeModule,
SwiperModule,
RouterModule.forRoot(routes),
ShareModule,
MasonryModule,
Ng4TwitterTimelineModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
tweets.component.ts
import { Component, OnInit } from '#angular/core';
import { Ng4TwitterTimelineService } from 'ng4-twitter-timeline/lib/index';
#Component({
selector: 'app-tweets',
templateUrl: './tweets.component.html',
styleUrls: ['./tweets.component.scss']
})
export class TweetsComponent implements OnInit {
constructor(private ng4TwitterTimelineService: Ng4TwitterTimelineService) {}
ngOnInit() {}
}
tweets.component.html
<ng4-twitter-timeline [dataSrc]="{sourceType: 'profile',screenName: 'lokers_one'}" [opts]="{tweetLimit: 2}"></ng4-twitter-timeline>
You should add .forRoot when you imports Ng4TwitterTimelineModule in #ngModule. So your app.module.ts should look like that:
...
import { BrowserModule } from '#angular/platform-browser';
import { NgModule } from '#angular/core';
import { AppRoutingModule } from './app-routing.module';
import { RouterModule } from '#angular/router';
import { SwiperModule } from 'angular2-useful-swiper';
import { AngularFontAwesomeModule } from 'angular-font-awesome/angular-font-awesome';
import { FormsModule } from '#angular/forms';
import { HttpModule } from '#angular/http';
import { ShareModule } from 'ng2share/share.module';
import { MasonryModule } from 'angular2-masonry';
import { routes } from './app-routing.module';
import { Ng4TwitterTimelineModule } from 'ng4-twitter-timeline/lib/index';
#NgModule({
declarations: [
...
],
imports: [
BrowserModule,
AppRoutingModule,
HttpModule,
AngularFontAwesomeModule,
SwiperModule,
RouterModule.forRoot(routes),
ShareModule,
MasonryModule,
Ng4TwitterTimelineModule.forRoot()
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
Figured it out, everyone. The account used in the demo has protected tweets... which is why nothing was embedding... I changed the account and it does work. But still don't understand why I'm still getting this error: 'ng4-twitter-timeline' is not a known element'

The selector "login-app" did not match any elements while using different component Angular 2

I have a component in angular 2 as shown below
login.component.ts
import { Component } from '#angular/core';
import { LoginViewModel } from "../ViewModel/Login.ViewModel";
import { LoginService } from "../Service/Login.Service";
#Component({
selector: 'login-app',
templateUrl: 'Account/partialLogin',
providers: [LoginViewModel, LoginService]
})
export class LoginComponent {
constructor(private loginservicemodel: LoginService, private model: LoginViewModel) {
this.model.userName = 'erere#ada.com';
this.model.password = "test anand";
}
save(modelValue: LoginViewModel, isValid: boolean) {
if (isValid) {
this.loginservicemodel.loginHttpCall();
}
}
}
Home.Component.ts
import { Component } from '#angular/core';
#Component({
selector: 'Home-app',
template: `
<h1>Angular Router</h1>
<nav>
<a routerLink="/crisis-center" routerLinkActive="active">Crisis Center</a>
<a routerLink="/heroes" routerLinkActive="active">Heroes</a>
</nav>
<router-outlet></router-outlet>
`
})
export class HomeComponent {
}
The appModule.ts
import { NgModule } from '#angular/core';
import { BrowserModule } from '#angular/platform-browser';
import { FormsModule } from '#angular/forms';
import { RouterModule, Routes } from '#angular/router';
import { HttpModule, JsonpModule } from '#angular/http';
import { LoginComponent } from "./Components/login.Component";
import { HomeComponent } from "./Components/home.component";
const appRoutes: Routes = [
{ path: '', component: HomeComponent },
{ path: 'Account/Login', component: LoginComponent }
];
#NgModule({
imports: [BrowserModule, FormsModule, HttpModule, JsonpModule, RouterModule.forRoot(appRoutes)],
declarations: [LoginComponent, HomeComponent],
bootstrap: [HomeComponent]
})
export class AppModule { }
login.cshtml
#{
ViewData["Title"] = "Login";
}
<login-app>looding...</login-app>
partialLogin.cshtml
<router-outlet></router-outlet>
<p>THis is test</p>
Routing
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}");
routes.MapRoute(
name: "spa-fallback",
template: "{*url}",defaults: new { controller = "Home", action = "Index" });
});
I have use the angular 2 routing as you can see in the appmodule.ts.If I navigate to homepage i,e Home/Index I will get an error as The selector "login-app" did not match any elements and when I navigate to Account/Login I will get an error as The selector "Home-app" did not match any elements.I know the the condition on appmodule is not working. How can I make this work. Please anyone can solve this issue
you are getting this error because you didn't import all your other component in you ngModule file. add them in declaration just like you have imported LoginComponent
#NgModule({
imports: [BrowserModule, FormsModule, HttpModule, JsonpModule],
declarations: [LoginComponent],<-- add all your component here
bootstrap: [LoginComponent]
})
export class AppModule { }
Below is an example of how to add route in Angular2:
//Create new app.module.ts file
import { ModuleWithProviders } from '#angular/core';
import { Routes, RouterModule } from '#angular/router';
import { LoginComponent } from './Components/login.Component';
const appRoutes: Routes = [
{ path: '', redirectTo: 'home', pathMatch: 'full' },
{ path: 'login', component: LoginComponent}
];
export const routing: ModuleWithProviders = RouterModule.forRoot(appRoutes);
//Import the above define route in your App module
import { NgModule } from '#angular/core';
import { BrowserModule } from '#angular/platform-browser';
import { FormsModule } from '#angular/forms';
import { HttpModule, JsonpModule } from '#angular/http';
import { LoginComponent } from "./Components/login.Component";
//Import your route file
import { routing } from './app.routing';
#NgModule({
imports: [BrowserModule, FormsModule, HttpModule, JsonpModule,routing,],
declarations: [LoginComponent],
bootstrap: [LoginComponent]
})
export class AppModule { }
Finally the working code.Call the respective selector in HTML page
AppModule.ts
import { NgModule } from '#angular/core';
import { BrowserModule } from '#angular/platform-browser';
import { FormsModule } from '#angular/forms';
import { RouterModule, Routes } from '#angular/router';
import { HttpModule, JsonpModule } from '#angular/http';
import { ModuleWithProviders } from '#angular/core';
import { AppComponent} from "./app.component";
import { LoginComponent } from "./Components/login.Component";
import { HomeComponent } from "./Components/home.component";
const appRoutes: Routes = [
{ path: '', redirectTo: 'Home/Index', pathMatch: 'full' },
{ path: 'Account/Login', component: LoginComponent },
{ path: 'Home/Index', component: HomeComponent }
];
export const routing: ModuleWithProviders = RouterModule.forRoot(appRoutes);
#NgModule({
imports: [BrowserModule, FormsModule, HttpModule, routing],
declarations: [AppComponent,LoginComponent, HomeComponent],
bootstrap: [AppComponent]
})
export class AppModule { }
app.Component.ts
import { Component } from '#angular/core';
import { Routes, RouterModule } from '#angular/router';
#Component({
selector: 'main-app',
template: '<router-outlet></router-outlet>'
})
export class AppComponent { }
Home.Component.ts
import { Component } from '#angular/core';
#Component({
selector: 'Home-app',
template: `
<h1>Angular Router</h1>
<nav>
<a routerLink="/crisis-center" routerLinkActive="active">Crisis Center</a>
<a routerLink="/heroes" routerLinkActive="active">Heroes</a>
</nav>
`
})
export class HomeComponent {
}
login.Component.ts
import { Component } from '#angular/core';
import { LoginViewModel } from "../ViewModel/Login.ViewModel";
import { LoginService } from "../Service/Login.Service";
#Component({
selector: 'login-app',
templateUrl: 'Account/partialLogin',
providers: [LoginViewModel, LoginService]
})
export class LoginComponent {
constructor(private loginservicemodel: LoginService, private model: LoginViewModel) {
this.model.userName = 'erere#ada.com';
this.model.password = "test anand";
}
save(modelValue: LoginViewModel, isValid: boolean) {
if (isValid) {
this.loginservicemodel.loginHttpCall();
}
}
}

Categories