I've tried this syntax in AngularDart 0.11.0: Angular Dart passing data from route service into a controller
module.value(RouteInitializerFn, configureRoutes);
void configureRoutes(Router router, RouteViewFactory views)
{
print("configureRoutes");
views.configure({
'login': ngRoute(
path: '/login',
view: 'login/login.tpl.html'),
'today': ngRoute(
path: '/today',
view: '/today/today.tpl.html')
});
However, my routing function never seems to get called. I've used both a print statement and breakpoint to no avail. When I attempt to call it like so:
WorkoutLoggerApplication(this.rootScope, this.router)
{
print("WorkoutLoggerApplication::constructor");
new Future.delayed(new Duration(seconds: 2), ()
{
router.go("login", {});
});
}
I get:
Bad state: Invalid route name: login
I've tried 0.10.0, but no dice. I've also tried 3 varieties of the new bind function format, both also don't seem to ever fire the routing function.
I've also struggled a lot with the current examples. I ended up with something like the example below. The NgRoutingUsePushState setting was necessary in 0.11.0 or changing routes didn't seem to work, may have been fixed on 0.12.0.
library myangular;
import 'package:angular/angular.dart';
import 'package:angular/application_factory.dart';
class MyModule extends Module {
MyModule() {
bind(RouteInitializerFn, toValue: myRouteInitializer);
bind(NgRoutingUsePushState, toFactory: (_) => new NgRoutingUsePushState.value(false));
}
}
void myRouteInitializer(Router router, RouteViewFactory views) {
views.configure({
'foo': ngRoute(
path: '/foo',
view: 'view/foo.html'),
'bar': ngRoute(
path: '/bar',
view: 'view/bar.html',
defaultRoute: true),
});
}
void main() {
applicationFactory()
.addModule(new MyModule())
.run();
}
This is the way I'm handling my routing now, it also took a while, but it's working in AngularDart 0.12.0
In your router file you'll have this code:
void configureRoutes(Router configureRoutes, RouteViewFactory view) {
configureRoutes.root
..addRoute(
name: 'login',
path: '/login',
enter: view('login/login.tpl.html')
)
..addRoute(
name: 'today',
path: '/today',
enter: view('today/today.tpl.html')
);
}
Then in your module initialization class you'll add this code:
import 'package:angular/angular.dart';
import 'package:angular/application_factory.dart';
import 'package:angular/routing/module.dart';
import 'package:logging/logging.dart';
// router config import
import 'my_router_config.dart';
class MainModule extends Module {
MainModule() {
this
// bind all you need and then bind routing
// ROUTING
..bind(RouteInitializerFn, toValue: configureRoutes)
..bind(NgRoutingUsePushState,
toFactory: (_) => new NgRoutingUsePushState.value(false));
}
void main() {
//some logging logic and then init
Logger.root.level = Level.FINEST;
Logger.root.onRecord.listen((LogRecord r) { print(r.message); });
applicationFactory()
.addModule(new MainModule())
.run();
}
}
Finally, to access the router in a Controller, you would simply do it like this:
#Controller(
selector: '[some-controller]',
publishAs: 'c')
class SomeController {
Router router;
SomeController(this.router) {
print(router);
}
}
Related
I am working on a simple project using NestJS.
I came here to ask for help because there was a problem while I was working on the project separating the controller and the service.
I am going to get the path value of the Get method from the controller and hand it over to the service.
In this process, the controller was set up as follows.
import { Controller, Get, Param, Post, Query } from '#nestjs/common';
import { AppService } from 'src/app.service.ts'
#Controller('app')
export class AppController {
constructor(private readonly appService: AppService) {}
#Get(':vendor/art/:artId')
findOneByVenderAndUid(
#Param('vender') vender: string,
#Param('artId') artId: string,
) {
return this.appService.findOneByVenderAndUid(vender, artId);
}
}
In addition, the global pipeline was set in main.ts as follows.
import { ValidationPipe } from '#nestjs/common';
import { NestFactory } from '#nestjs/core';
import { AppModule } from './app.module';
async function bootstrap() {
const app = await NestFactory.create(AppModule);
app.useGlobalPipes(
new ValidationPipe({
whitelist: true,
forbidNonWhitelisted: true,
transformOptions: {
enableImplicitConversion: true,
},
}),
);
await app.listen(3000);
}
bootstrap();
However, when I output the path value received from the service to the console, it appeared as undefined and could not be used.
Is there anything wrong with the part that I implemented?
Typo in the #Param(). The string passed to the annotation must mat ch the string used in the url. In this case :vendor does not match #Param('vender')
I followed code SignalR guide for .NET CORE AngularApp
I get below error:
Failed to start the connection: Error: Unable to initialize any of the available transports
The code is there hosted on Microsoft's Github here
Below is code snippet from Startup.cs code:
public class Startup
{
public void ConfigureServices(IServiceCollection services)
{
services.AddCors(o => o.AddPolicy("CorsPolicy", builder => {
builder
.AllowAnyMethod().AllowAnyHeader()
.WithOrigins("http://localhost:49446")
.AllowCredentials();
//.AllowAnyOrigin()
}));
services.AddSignalR();
...
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
app.UseCors("CorsPolicy");
app.UseSignalR(routes =>
{
routes.MapHub<NotifyHub>("/notifyhub");
});
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller}/{action=Index}/{id?}");
});
...
}
}
My Hub class:
public class NotifyHub:Hub<ITypedHubClient>
{
public NotifyHub()
{
}
}
Angular app.component.ts:
import {Component} from '#angular/core';
import {HubConnection, HubConnectionBuilder, IHubProtocol} from '#aspnet/signalr';
#Component({selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css']})
export class AppComponent {
public _hubConnection : HubConnection;
msgs : Message[] = [];
constructor() {}
ngOnInit() : void {
let builder = new HubConnectionBuilder();
this._hubConnection = builder
.withUrl('/notifyhub')
.build();
this
._hubConnection
.start()
.then(() => console.log('Connection started!'))
.catch(err => console.log('Error :', err));;
this
._hubConnection
.on('BroadcastMessage', (type : string, payload : string) => {
this
.msgs
.push({severity: type, summary: payload});
});
}
}
Not sure what am I missing here? Please advise. Thank you.
Ok, so issue was mismatch of .NET Core version and #aspnet/signalr version.
I am using .NET core version 1.0.0-preview1-final
but #aspnet/signalr I was using was 1.0.0.
So, I fixed the issue by changing the #aspnet/signalr version from 1.0.0 to 1.0.0-preview1-final which fixed the issue. Github is updated.
I've been trying to troubleshoot a strange problem with angular 2 where it isn't detecting my provider declaration, but nothing is working. I can't even replicate it in plunkr.
I'm using angular 2 rc 3 with router 3.0 alpha.8.
Error message is: ORIGINAL EXCEPTION: No provider for TestService!
app.routes.ts:
import { provideRouter, RouterConfig } from '#angular/router';
import { HomeComponent } from './app/home/home.component';
import { LogInComponent } from './app/log-in/log-in.component';
import { SignUpComponent } from './app/sign-up/sign-up.component';
export const routes: RouterConfig = [
{ path: '', component: HomeComponent },
{ path: 'log-in', component: LogInComponent },
{ path: 'sign-up', component: SignUpComponent }
];
export const APP_ROUTER_PROVIDERS = [
provideRouter(routes)
];
main.ts:
import { bootstrap } from '#angular/platform-browser-dynamic';
import { enableProdMode } from "#angular/core";
import { AppComponent } from './app/app.component';
import { APP_ROUTER_PROVIDERS } from './app.routes';
// enableProdMode();
bootstrap(AppComponent, [
APP_ROUTER_PROVIDERS
])
.catch(error => console.log(error));
app/app.component.ts:
import { Component } from '#angular/core';
import { ROUTER_DIRECTIVES } from '#angular/router';
import { TestService } from './shared/test.service';
#Component({
selector: 'my-app',
template: `
<div id="menu">
<a [routerLink]="['/sign-up']"><button>Sign Up</button></a>
</div>
<router-outlet></router-outlet>
`,
directives: [ROUTER_DIRECTIVES],
providers: [TestService]
})
export class AppComponent {
constructor() { }
}
app/sign-up/sign-up.component.ts:
import { Component } from '#angular/core';
import { ROUTER_DIRECTIVES } from '#angular/router';
import { TestService } from '../shared/test.service';
#Component({
selector: 'sign-up',
template: `<h1>Sign up!</h1>`,
directives: [ROUTER_DIRECTIVES]
})
export class SignUpComponent {
constructor(private testService: TestService) {
this.testService.test('works?');
}
}
app/shared/test.service.ts:
import { Injectable } from '#angular/core';
#Injectable()
export class TestService {
constructor() { }
test(message: string) {
console.log(message);
}
}
So, I'm providing the testservice in the base component (app.component.ts) because I want all my components to access the same instance. However, when I navigate to sign-up, I get the no provider for testservice error. If I provide the TestService within the sign-up component, this then works:
import { Component, OnInit } from '#angular/core';
import { ROUTER_DIRECTIVES } from '#angular/router';
import { TestService } from '../shared/test.service';
#Component({
selector: 'sign-up',
template: `<h1>Sign up!</h1>`,
directives: [ROUTER_DIRECTIVES],
providers: [TestService]
})
export class SignUpComponent implements OnInit {
constructor(private testService: TestService) { }
ngOnInit() { }
}
However, I need the same instance accessible throughout my app, so how can I inject this at the main component level?
I even tried replicating this app-level service providing with plunkr with the same version of everything, but it doesn't seem to give me the same error...
http://plnkr.co/edit/5bpeHs72NrlyUITCAJim?p=preview
Injecting something on the app level is done in bootstrap:
main.ts:
import { TestService } from '../shared/test.service';
bootstrap(AppComponent, [
APP_ROUTER_PROVIDERS, TestService
])
For me, some references to the "services" folder were "Services". When I made them all "services" (lower case), it worked.
For example:
import {ApiService} from "./Services/api.service";
didn't work, but this worked:
import {ApiService} from "./services/api.service";
To All future readers - and this is correct for angular 2.0.0 rc-4:
make sure that you follow the below folder structure:
root:
index.html
package.json
systemjs.config.js
tsconfig.json (if using TypeScript)
typings.json
app (folder):
- main.js (the root script for your app)
- app.component.js (the root component for the entire app)
This is crucial for the hierarchical injection to properly scope and identify providers.
Also, and this is very important - if still encountering problems and you are using TypeScript or any other transpiled language- delete any artifacts which your transpiler produces for every associated class in the problematic object graph - this, and the OP's answer eventually helped in my case (*.map.js and *.js files deleted and re-transpiled).
It was a configuration issue after all, and a completely elusive one at that.
Per the ang2 style guide, I had my main.ts one folder up from my main app folder, and in systemjs.config I had to declare the main for app as '../main.js'. When I moved the main file to the root app folder and changed the package declaration in systemjs to 'main.js' it worked.
The odd thing is everything else worked, right up until I try to utilize hierarchical dependency injection.
I'm creating a single page web app using polymer.dart and wants to deploy it on google app engine. I'm stack at routing
I'm using redstone and shelf_static for my server and route_hierarchical for my client.
bin/server.dart
import 'package:appengine/appengine.dart';
import 'package:redstone/server.dart' as app;
import 'package:shelf_static/shelf_static.dart';
main() {
var staticHandler = createStaticHandler("web",
defaultDocument: "index.html", serveFilesOutsidePath: true);
app.setShelfHandler(staticHandler);
app.setupConsoleLog();
app.setUp();
runAppEngine(app.handleRequest);
}
lib/main_app/main_app.dart
import 'package:polymer/polymer.dart';
import 'package:route_hierarchical/client.dart';
#CustomTag('main-app')
class MainApp extends PolymerElement {
final Router router = new Router();
MainApp.created() : super.created();
ready() {
print("Main App: ready()");
router.root
..addRoute(name: 'home', path: '/', enter: showHome, defaultRoute: true)
..addRoute(name: 'login', path: '/#!/login', enter: showLogin);
router.listen();
}
void showHome(RouteEvent event) {
print("Main App: showHome()");
}
void showLogin(RouteEvent event) {
print("Main App: showLogin()");
}
}
lib/main_app/main_app.html
web/index.html
Pages
Home: localhost:8080/
Login: localhost:8080/#!/login
If I run the app locally using "pub serve" command, it works.
However if i run it on appengine using "gcloud preview app run app.yaml" command, the login route isn't working and logs an error.
http://prntscr.com/77adww
I finally got it working! The problem was, I was running the untransformed output just like #Jake MacDonald said. here's how
replace
var staticHandler = createStaticHandler("web", defaultDocument: "index.html", serveFilesOutsidePath: true);
with
var staticHandler = createStaticHandler("build/web", defaultDocument: "index.html", serveFilesOutsidePath: true);
To call ngBootstrap I used
void main() {
initPolymer()
.run(() {
ngBootstrap(module: new AppModule());
});
}
Since polymer 0.10.0-pre.8 this seems not possible anymore:
Dartium currently only allows a single Dart script tag per application, and in the future it will run them in separtate isolates. To prepare for this all the following script tags need to be updated to use the mime-type "application/dart;component=1" instead of "application/dart":
⪪script type="application/dart" src="main.dart"></script>
Only one Dart script tag allowed per document
But my main is not a component - it is a regular main!!!
Was easier than thought.
index.html:
<head>
<script type='application/dart;component=1' src='main.dart'></script>
</head>
main.dart:
import 'package:polymer/polymer.dart';
import 'package:angular/angular.dart';
import 'package:angular/angular_dynamic.dart';
// HACK until we fix code gen size. This doesn't really fix it,
// just makes it better.
#MirrorsUsed(override: '*')
import 'dart:mirrors';
void myRouteInitializer(Router router, RouteViewFactory views) {
views.configure({
'hello': ngRoute(
path: '/hello',
enter: views('views/hello.html')),
'goodbye': ngRoute(
path: '/hellopolymer/:callerID',
enter: views('views/hello-polymer.html'))
});
}
#NgController( selector: '[webapp-sample]', publishAs: 'ctrl')
class MyControler {
final Repository _repository;
MyControler(final RouteProvider routeProvider,this._repository) {
final int value = routeProvider.parameters["callerID"];
if(value != null && value != null) {
_repository.value = value;
}
}
int get value => _repository.value;
}
class Repository {
int value = 0;
}
class AppModule extends Module {
AppModule() {
value(RouteInitializerFn, myRouteInitializer);
value(Repository,new Repository());
type(MyControler);
factory(NgRoutingUsePushState, (_) => new NgRoutingUsePushState.value(false));
}
}
#initMethod
void init() {
dynamicApplication().addModule(new AppModule()).run();
}