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);
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 am trying to develop an application with Spring Boot for the back end and Angular 2 for the front end, using maven.
The angular 2 front end is in the src/main/resources/static dir of the project.
When I enter the http://localhost:8080/ URL in my browser, all is fine: I can access the angular 2 front end, and the front end can communicate with the rest api perfectly. My angular 2 routing works fine: when I click on a link on the front end, I go the right page and the browser url bar shows the right things (ie. http://localhost:8080/documents)
But the problem is when I try to directly write the same URL in the browser. Spring take over the front end and says the is no mapping for /documents.
Is there a way to tell spring boot to only "listen" to /api/* URL and to "redirect" all the others to the front end?
Here is my Spring Controller class:
#RestController
#RequestMapping("/api")
public class MyRestController {
#Autowired
private DocumentsRepository documentRepository;
#CrossOrigin(origins = "*")
#RequestMapping(value = "/documents/list",
method = RequestMethod.GET,
produces = "application/json")
public Iterable<RfDoc> findAllDocuments() {
return documentRepository.findAll();
}
}
Here is the main application class:
#SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
Here is my app.route.ts:
import { provideRouter, RouterConfig } from '#angular/router';
import { DocumentComponent } from './doc.component';
const routes: RouterConfig = [
{
path: '',
redirectTo: 'documents',
pathMatch: 'full'
},
{
path: "documents",
component: DocumentComponent
}
];
export const appRouterProviders = [
provideRouter(routes)
];
Ok, so I found a perfectly fine solution (for me, at least): I change my location for the old AngularJS 1.X way, with the # in the URL (i.e. http://localhost:8080/#/documents ).
To obtain this behaviour, I change my bootstrap like this
import { bootstrap } from '#angular/platform-browser-dynamic';
import { HTTP_PROVIDERS } from '#angular/http';
import { AppComponent } from './app.component';
import { appRouterProviders } from './app.routes';
import { AuthService } from './auth.service';
bootstrap(AppComponent, [AuthService,
appRouterProviders,
HTTP_PROVIDERS,
{ provide: LocationStrategy, useClass: HashLocationStrategy }
]);
Hope this can help somebody!
I have a problem in angular 2 in typescript that browser is not making HTTP Call. I dont see any HTTp call in network section in browser.
the angular code works when i dont have any http call in service and it brings data when i use HTTP it doenst make any http request
Following is my code.
<script src="~/lib/es6-shim.min.js"></script>
<script src="~/lib/system-polyfills.js"></script>
<script src="~/lib/shims_for_IE.js"></script>
<script src="~/lib/angular2-polyfills.js"></script>
<script src="~/lib/system.js"></script>
<script src="~/lib/Rx.js"></script>
<script src="~/lib/angular2.dev.js"></script>
<script src="~/lib/http.dev.js"></script>
<script src="~/lib/router.dev.js"></script>
SERVICE :
import {Injectable} from 'angular2/core';
import {Http, Response} from 'angular2/http';
import {Observable} from 'rxjs/Observable';
#Injectable()
export class AuthService {
private _authPath = 'http://api/Auth';
constructor(private http: Http) { }
getAuthSettings() {
return new Promise((resolve, reject) => {
return this.http.get(this._authPath).toPromise().then((val: Response) => resolve(val.text()));
});
}
private handleError(error: Response) {
// in a real world app, we may send the error to some remote logging infrastructure
// instead of just logging it to the console
console.error(error);
return Observable.throw(error.json().error || 'Server error');
}
}
main MODULE :
import { Component } from 'angular2/core';
import {AuthService} from './auth.service';
import {OnInit} from 'angular2/core';
import {HTTP_PROVIDERS} from 'angular2/http';
#Component({
selector: "main-app",
template: "{{title}}",
providers: [HTTP_PROVIDERS, AuthService]
})
export class AppComponent implements OnInit {
public title: string = '';
constructor(private _authService: AuthService) {
}
ngOnInit() {
//this.title = "aaa";
this._authService.getAuthSettings().then((val: string) => {
this.title = val;
});
//this._authService.getAuthSettings().subscribe((val: string) => this.title = val)
}
};
I dont see any HTTP call in network section in browser.
There might be some filters preventing you from seeing it. To be sure update the code as follows:
console.log('starting');
this._authService.getAuthSettings()
.then((val: string) => {
this.title = val;
console.log('success');
},() => console.log('fail'));
console.log('waiting');
And see which logs happen. Hopefully it helps. Sorry if it doesn't ๐น
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);
}
}
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();
}