Access router from Angular Dart controller - dart

I have a basic Angular Dart program which currently allows logging in and shows a basic dashboard when logged in. What I would like to do is redirect to the dashboard route after a successful login. I do not know how to access the router object from within the login controller, attempts to use DI to load in Router to the controller work but give me a fresh Router object instead of the previously initialised one (as expected).
main.dart
import 'package:angular/angular.dart';
import 'dart:convert' show JSON;
import 'dart:html';
class TTRouter implements RouteInitializer {
Cookies _cookies;
TTRouter(this._cookies);
init(Router router, ViewFactory view) {
router.root
..addRoute(
name: 'login',
path: '/login',
enter: view('login.partial.html'))
..addRoute(
name: 'home',
path: '/dashboard',
enter: view('dashboard.partial.html'));
}
}
#NgController(
selector: '[login-controller]',
publishAs: 'ctrl')
class LoginController {
Http _http;
Scope _scope;
LoginController(this._scope, this._http);
login() {
// Login API request ommitted
// TODO: insert redirect to 'home' route here
}
}
class TTModule extends Module {
TTModule() {
type(RouteInitializer, implementedBy: TTRouter);
type(LoginController);
factory(NgRoutingUsePushState,
(_) => new NgRoutingUsePushState.value(false));
}
}
main() => ngBootstrap(module: new TTModule());
login() is called using ng-submit="ctrl.login() from the login partial view.
I would be grateful for any comments on the structure of the code as well if I'm approaching this the wrong way. I am new to both Dart and Angular (read/watched tutorials but this is the first app I am building on my own).

If you add the router as value to the module instead of type you get the same instance every time.
TTModule() {
value(RouteInitializer, new TTRouter());
}

try with NgRoutingHelper.
class LoginController {
Http _http;
Scope _scope;
NgRoutingHelper locationService;
LoginController(this._scope, this._http, NgRoutingHelper this.locationService );
login() {
// Login API request ommitted
// TODO: insert redirect to 'home' route here
locationService.router.go('home', {} );
}
}
don't forget to add the service in your module
type(NgRoutingHelper );

You should be always getting the same instance of the Router -- there can only be one, otherwise unpredictable things will start happening.
class LoginController {
Http _http;
Scope _scope;
Router _router;
LoginController(this._scope, this._http, this._router);
login() {
_router.go('home', {} );
}
}

Related

ASP.Net Core + Angular 2 app /home routing

I've been fighting with this for a while now and decided to write a post.
I'm building a simple Single Page Application using VS2017 on ASP.Net Core 5.0 and Angular 2 over a template taken from ASP.NET Core Template Pack. The app is supposed to manage a contact list database.
The idea I have in mind is that the default starting '/home' page should be displaying the list of contacts using HomeComponent. All routing works fine, but when app is getting started or whenever I'm trying to route to '/home', it keeps going to ASP Home view's Index.cshtml page instead of using Angular routing.
Any idea how to make it go through Angular at all times? I wanted to align the HomeComponent with '/home' route but instead it keeps going to ASP page which is only there to say 'Loading...' which I don't really need (I think).
I've tried a lots of different solution but I wasn't able to get anything to work. I might be missing something obvious here as I'm not too advanced on these grounds, so if you can keep it basic, please do ;-)
Here's my Configure method from Startup.cs:
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
loggerFactory.AddConsole(Configuration.GetSection("Logging"));
loggerFactory.AddDebug();
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
app.UseWebpackDevMiddleware(new WebpackDevMiddlewareOptions
{
HotModuleReplacement = true
});
}
else
{
app.UseExceptionHandler("/Home/Error");
}
app.UseStaticFiles();
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index" });
routes.MapSpaFallbackRoute(
name: "spa-fallback",
defaults: new { controller = "Home", action = "Index",});
});
}
app.module.shared.ts:
import { NgModule } from '#angular/core';
import { RouterModule } from '#angular/router';
import { AppComponent } from './components/app/app.component'
import { NavMenuComponent } from './components/navmenu/navmenu.component';
import { DetailsComponent } from './components/details/details.component';
import { EditComponent } from './components/editContact/editContact.component';
import { NewContactComponent } from './components/newContact/newContact.component';
import { HomeComponent } from './components/home/home.component';
import { ContactServices } from './services/services';
export const sharedConfig: NgModule = {
bootstrap: [ AppComponent ],
declarations: [
AppComponent,
NavMenuComponent,
DetailsComponent,
EditComponent,
NewContactComponent,
HomeComponent
],
providers: [ContactServices],
imports: [
RouterModule.forRoot([
{ path: '', redirectTo: 'home', pathMatch: 'full' },
{ path: 'home', component: HomeComponent },
{ path: 'details', component: DetailsComponent },
{ path: 'new', component: NewContactComponent },
{ path: '**', redirectTo: 'home' }
])
]};
ASP's Home Index.cshtml:
#{
ViewData["Title"] = "Home Page";
}
<app>Loading...</app>
<script src="~/dist/vendor.js" asp-append-version="true"></script>
#section scripts {
<script src="~/dist/main-client.js" asp-append-version="true"></script>
}
Aaaand home.component.ts:
import { Component } from '#angular/core';
import { ContactServices } from '../../services/services';
import { Response } from '#angular/http';
#Component({
selector: 'home',
templateUrl: './home.component.html'
})
export class HomeComponent {
public ContactList = [];
public constructor(private conService: ContactServices) {
this.conService.getContactList()
.subscribe(
(data: Response) => (this.ContactList = data.json())
);
}
}
Thanks in advance guys! Any advice will be appreciated.
I think that what is troubling you is that you wish to have Single App and have Angular doing client routing and posting WEB.API calls back to .NET Core Web API.
So, once you are on some page like www.example/subpage, and you press F5 to reload the same, avoid being kicked back to the homepage.
The solution is to create two MVC routes.
The first route will deal with redirecting a call to Web.API and the second one will accept any Angular URL request, and just ignore everything and forward the call to the Home controller.
To achieve that you need:
1. In Views\Home\Index.cshtml include your Angular component tag (my is app-root)
2. In Startup.cs, just before "app.Run" add the following code
app.UseMvc(cfg => {
cfg.MapRoute(
"API",
"api/{controller=*}/{action=*}/{id?}");
cfg.MapRoute(
"Default", // Route name
"{*catchall}", // URL with parameters
new { controller = "Home", action = "Index" });
});
I took different approach and rebuilt my application using the tutorial found under this link.
It is a solution where you first create ASP.NET CORE Web App API interface and install Angular over it. A little bit of 'engineering', works directly off Visual Studio and takes little time to set up.
Is there a reason why you are using asp.net with angular? I HIGHLY suggest you using angular cli. Importing libraries and publishing is very difficult with angular + asp.net.
Using angular cli will also always be "angular"

in AngularDart how to register a PreEnter event to a route which needs to use a service method?

After all the deprecation in AngularDart , now configuring routes via the below initRoutes method inside my modules constructor.
//inside the main of the appliction
..
this.bind(RouteInitializerFn, toValue:initRoutes);
this.bind(NgRoutingUsePushState, toFactory:(_) => new NgRoutingUsePushState.value(false));
//in routeconfig.dart file which is imported in the main.dart
void initRoutes(Router router, RouteViewFactory viewFactory) {
viewFactory.configure({
'loginPage': ngRoute(
path: '/loginPage',
view: 'view/loginPage.html'),
'landingPage': ngRoute(
path: '/landingPage',
view: 'view/landingPage.html',
defaultRoute: true,
enter: _checkAuthentication
...
My question is how to inject the Service class which has the _checkAuthentication method in routeconfig.dart ? Since it's not a class how can get the dependency injection here ? or is there another way to initialize and register the RouteInitializerFn in the Module contructor ?
You can use the following technique: functions can be implemented as classes with the 'call' method.
#Injectable()
class MyRouteInitializer implements Function {
AuthService service;
MyRouteInitializer(this.service);
call(Router router, RouteViewFactory viewFactory) {
...
service._checkAuthentication();
...
}
}
Function registration in the module:
this.bind(RouteInitializerFn, toImplementation: MyRouteInitializer);

How to inject services into RouteInitializerFn (new routing DSL)

I'm switching my app over to the new routing DSL. Specifically, I want to do something like this with preEnter:
final RouteInitializerFn routes =(Router router, ViewFactory views) {
views.configure({
'chat': ngRoute(
path: '/chat',
// authService.requireState returns a Future<bool>, and may invoke an HttpRequest
preEnter: (RoutePreEnterEvent e) => e.allowEnter(authService.requireState(LOGGED_IN)),
view: 'views/chat.html'),
'login': ngRoute(
path: '',
defaultRoute: true,
view: 'views/login.html')
});
}
This would be configured in the module as follows:
value(RouteInitializerFn, routes);
In case you missed it, I'm referencing an injectable authService within the RouteInitializerFn. This isn't possible since RouteInitializerFn is a function and not a class, so nothing can be injected into it. If I encapsulated the routes function within a class, I'm not sure how I could configure RouteInitializerFn, so I'm in a bit of a quandary.
I found a pretty cool solution to this problem. Turns out, if you define a call method on a class that satisfies a typedef, you can configure it as an implementation of the typedef. Very cool. Here is my solution:
class Routes
{
final UserService _userService;
Routes(this._userService);
void call(Router router, ViewFactory views)
{
views.configure({
'chat': ngRoute(
path: '/chat',
preEnter: (RoutePreEnterEvent e) => e.allowEnter(this._userService.requireUserState(UserService.LOGGED_IN)),
view: 'views/chat.html'
),
'login': ngRoute(
path: '',
defaultRoute: true,
view: 'views/login.html'
)
});
}
}
and this is how it's configured within the module:
// old syntax
type(RouteInitializerFn, implementedBy: Routes);
// new syntax
bind(RouteInitializerFn, toImplementation: Routes);

How do I get routes to work with AngularDart?

This is my code,
import 'package:angular/angular.dart';
class AppModule extends Module {
AppModule(){
type(AppController);
type(LoginController);
type(RouteInitializer, implementedBy: AppRouter);
}
}
class AppRouter implements RouteInitializer {
init(Router router, ViewFactory view) {
router.root
..addRoute(
name: 'login',
path: '/login',
enter: view('app/views/login.tpl.html'))
..addRoute(
defaultRoute: true,
name: 'index',
enter: view('app/views/index.tpl.html'));
}
}
#NgController(selector: '[app-ctrl]', publishAs: 'ctrl')
class AppController {
}
#NgController(selector: '[login-ctrl]', publishAs: 'ctrl')
class LoginController {
Http _http;
String works = 'Works.';
LoginController(this._http);
}
No routes are working, clicking on a '#/login' link does not change the url or the view.
Log says
clicked /app/web/index.html#/login
route /app/web/index.html [Route: null]
route [Route: index]
What am I doing wrong?
There might be a couple of problems with this code. From what I can see the most likely problem is that the routing is using pushState. When you use pushState you don't manipulate the url using a hash. For more information on that see:
Manipulating Browser History
Angular will use push state when a browser supports it.
bind(NgRoutingUsePushState, toValue: new NgRoutingUsePushState.value(false));
Giving you are module of:
class AppModule extends Module {
AppModule(){
bind(AppController);
bind(LoginController);
bind(RouteInitializer, implementedBy: AppRouter);
bind(NgRoutingUsePushState, toValue: new NgRoutingUsePushState.value(false));
}
}
Other possible problems include:
Not having an ng-view directive
Not setting the ng-bind-route in app/views/login.tpl.html, and app/views/index.tpl.html
When I made all these changes your code worked correctly for me when navigating to #/login

RESTful routing in FuelPHP

Hello I am having some difficulty setting up a RESTful routing for a login controller. I keep getting hit with a status 404. Here is what I have so far. Any ideas?
In my routes:
'login' => array(
array('GET', new Route('session/login')),
array('POST', new Route('session/login'))
),
And in my sessions controller I have:
class Controller_Session extends Controller_Template {
public function get_login(){
return View::forge('session/login');
}
public function post_login() {
return View::forge('session/login',$data);
}
}
Try it using the default routing and the Rest controller.
class Controller_Session extends Controller_Rest
{...}
Delete the routes you set up and try accessing the Controller using {url}/session/login
basically delete all routes you have created.
Then create a controller session.php:
class Controller_Session extends Controller_Rest
//class Controller_Session extends Controller_Hybrid
{
public function get_login()
{
return View::forge('session/login');
}
public function post_login()
{
return View::forge('session/login',$data);
}
}
You can extend Controller_Hybrid, if you want to access to both rest and non-rest methods.
Now try with jquery to access url: '/session/login'
It should work!
Good luck
It was an Apache error. The mod rewrite module was not activated on a Debian Based OS

Resources