I am having issues setting up my Angular project with .NET MVC 5.0. I am not sure what's wrong with the below code. When I run the application, unexpectedly to me, app shows the template set in app-component.ts and not login
const appRoutes: Routes = [
{ path: '', redirectTo: 'login', pathMatch:'full' },
{ path: 'login', component: LoginComponent },
// otherwise redirect to home
{ path: '**', redirectTo: 'login' }
];
To test out the things, and ignore MVC controller/view routing for a second, I also tried creating html file inside in my login folder,
#Component({
moduleId: module.id,
templateUrl: 'login-component.html' -- This was initially /Public/Login -Path to the MVC controller
})
Project is shared on a github project here
https://github.com/GAK-MPRO/AngularMVCStarter/tree/Master/A2Rnd
My question is.. what do I need to do to route my views using MVC routing with views rendered by calling controllers.
Change the order in which your routes are defined. The default routes should always be at the end of the route list:
const appRoutes: Routes = [
{ path: 'login', component: LoginComponent },
{ path: '', redirectTo: 'login', pathMatch:'full' },
// otherwise redirect to home
{ path: '**', redirectTo: 'login', pathMatch:'full' }
];
I just looked at your code on git hub. The bootstrap module is trying to bootstrap appcomponent and the appcomponent does not have an router-outlet tag. Edit the template in the app.component.ts file to include
<router-outlet></router-outlet>
and it should show you both app component and login components html content.
import { Component } from '#angular/core';
#Component({
selector: 'my-app',
template: '<h1>Hello {{name}}</h1><br/><router-outlet></router-outlet>',
})
export class AppComponent { name = 'Angular'; }
Related
I have a React frontend using Rails 6 as an API. Webpacker is configured to package image files in app/javascript/media to app/javascript/packs. As far as I can tell, Webpack is creating the packs correctly; the packs folder contains my bundle.js, bundle.js map, and the .svg file bundled by webpack. Bundle.js is running fine, but when I try and import the image in a component, I'm getting a routing error stating:
ActionController::RoutingError (No route matches [GET] "/img.svg")
All of the questions I've seen about this mention that static assets don't get served by Rails in production mode without further configuration, but I have Rails in development mode and webpack-dev-server running.
Here's my webpack.config.js:
const path = require('path');
module.exports = {
context: __dirname,
entry: './frontend/app_name.jsx',
output: {
path: path.resolve(__dirname, 'app', 'javascript', 'packs'),
publicPath: path.resolve(__dirname, 'app', 'javascript', 'packs'),
filename: 'bundle.js'
},
resolve: {
extensions: ['.js', '.jsx', '*']
},
module: {
rules: [
{
test: /\.jsx?$/,
exclude: /(node_modules)/,
use: {
loader: 'babel-loader',
query: {
presets: ['#babel/env', '#babel/react']
}
},
},
{
test: /\.(png|svg)?$/,
loader: 'file-loader',
options: {
name: '[name].[ext]'
}
}
]
},
devtool: 'source-map'
};
Update: My routes.rb contains:
Rails.application.routes.draw do
root 'static#index'
namespace :api, defaults: { format: :json } do
resources :search, only: [:index]
end
end
and my static controller is
class StaticController < ApplicationController
def index
render :index
end
end
Should requests for static assets compiled by webpacker even be making it to the backend in a one page app?
I have a simple Ember 2.4 application. Here's the relevant code
../models/invitation.js
import DS from 'ember-data';
export default DS.Model.extend({
email: DS.attr('string')
});
../controllers/index.js
import Ember from 'ember';
export default Ember.Controller.extend({
emailAddress: '',
actions: {
saveInvitation() {
const email = this.get('emailAddress');
const newInvitation = this.store.createRecord('invitation', {
email: email,
});
newInvitation.save();
}
}
});
When I trigger the saveInvitation action, my Rails backend does not receive any parameters. The right action/controller receives the request but the only parameters are {action: "create", controller: "invitations"}.
Am I missing something? Shouldn't the parameters include the invitation with the email?
It seems that the default Ember adapter sends a content type application/vdn.api+json which is not automatically registered by Rails and parse the JSON arguments.
A fix for this was to register the right mime types under rails config
api_mime_types = %W(
application/vnd.api+json
text/x-json
application/json
)
Mime::Type.unregister :json
Mime::Type.register 'application/json', :json, api_mime_types
See https://github.com/rails-api/active_model_serializers/issues/1027
add following to config/initializers/json_adapter.rb
ActiveSupport.on_load(:action_controller) do
require 'active_model_serializers/register_jsonapi_renderer'
end
This may helps
I have an Ember CLI app that uses Rails as a backend. The code appears to be fine, and if I visit localhost:3000, it displays the JSON output just fine. However, Ember does not display this data.
Here is what I have so far:
// ember/app/adapters/application.js
import DS from "ember-data";
export default DS.ActiveModelAdapter.extend({
namespace: 'api'
});
// ember/app/controllers/data_keys.js
export default Ember.ArrayController.extend({
sortProperties: ['name']
});
// ember/app/models/data_key.js
export default DS.Model.extend({
name: DS.attr('string')
});
// ember/app/routes/data_keys/index.js
export default Ember.Route.extend({
controllerName: 'data_keys',
model: function() {
return this.store.all('data_key');
}
});
// rails/app/controllers/api/data_keys_controller.rb
class Api::DataKeysController < ApplicationController
def index
render json: DataKey.all
end
end
// rails/app/serializers/data_key_serializer.rb
class DataKeySerializer < ActiveModel::Serializer
attributes :id, :name
end
// rails/config/routes.rb
Rails.application.routes.draw do
namespace :api do
resources :data_keys
end
end
To run the app, I run the Rails side with rails s, then in another terminal tab I run ember server --proxy http://localhost:3000.
Is there something obvious that I'm missing? I know that Ember CLI version 0.0.39 had proxy uses, but I'm using Ember CLI 0.0.40.
ember -v
version: 0.0.40
node: 0.10.28
npm: 1.4.21
Here's an example of the JSON returned by the server:
{
"data_keys": [{
"id": 1,
"name": "foo"
}, {
"id": 2,
"name": "bar"
}]
}
I think that when you use DS.Store#all you're only filtering the records that are already in the store. You'll want to use DS.Store#find in order to get the records from the server.
export default Ember.Route.extend({
controllerName: 'data_keys',
model: function() {
return this.store.find('data_key');
}
});
Also, your ember files should use dashes rather than underscores.
I have followed all the github issues on HTML5Mode breaking Angular apps in 1.5. I am having the same problem but none of the fixes are working for me.
Im doing the following:
<base href="/">
and
get '/*path', :to => "menus#index"
and
app.config(function($routeProvider, $locationProvider) {
$locationProvider.html5Mode(true);
.when("/users/:u_id/restaurants/:r_id/menus/:m_id/edit", { templateUrl: "/assets/menus/edit.html", controller: "MenuSectionCtrl" })
.when("/users/:u_id/restaurants/:r_id/menus/:m_id/sections/:sec_id/items", { templateUrl: "/assets/menus/items.html", controller: "MenuItemCtrl" })
.when("/users/:u_id/restaurants/:r_id/menus/:m_id/sections/:sec_id/items/:i_id/option_sections", { templateUrl: "/assets/menus/option_sections.html", controller: "MenuOptionSectionCtrl" })
.when("/users/:u_id/restaurants/:r_id/menus/:m_id/sections/:sec_id/items/:i_id/option_sections/:op_sec_id/options", { templateUrl: "/assets/menus/options.html", controller: "MenuOptionCtrl" })
});
I am lost as to what to do next. I have tried every combination of routes and base[href].
Anybody have any ideas?
Also, I have followed this tutorial too. http://omarriott.com/aux/angularjs-html5-routing-rails/
Try this link
http://start.jcolemorrison.com/angularjs-rails-4-1-and-ui-router-tutorial/
If you have mount only single angularjs application then it is very straight forward. You need to make this entry in routes.rb
get '*path' => 'application#index'
And in your application.controller change the index method as below
def index
render layout: 'application'
end
The following link helped me to use rack-rewrite get which seems to work for me. Here is the link. Only the following code in config.ru would allow /api routes to rails:
# config.ru
# This file is used by Rack-based servers to start the application.
use Rack::Rewrite do
rewrite %r{^(?!.*(api|\.)).*$}, '/index.html'
end
require ::File.expand_path('../config/environment', __FILE__)
run Rails.application
I managed to get mine working with:
get '*path', to: redirect('/#/%{path}')
The template I bought was working without hash after the first load but if you refresh the page it does not work. I tried manually adding the hash like /#/page and the above routing does it automatically.
Hi I followed a tutorial: http://omarriott.com/aux/angularjs-html5-routing-rails/
Here's my manual.js.coffee.erb
# Place all the behaviors and hooks related to the matching controller here.
# All this logic will automatically be available in application.js.
# You can use CoffeeScript in this file: http://coffeescript.org/
#= require_tree ./templates
#Bento = angular.module('bento', ['ngRoute', 'ngResource', 'ngSanitize', 'ui.bootstrap', 'infinite-scroll'])
# Pre-cache templates
Bento.run ($window, $templateCache) ->
templates = $window.JST
for fileName of templates
fileContent = templates[fileName]
$templateCache.put(fileName, fileContent)
# Note that we're passing the function fileContent,
# and not the object returned by its invocation.
#= require_tree ./controllers
#= require_tree ./services
#= require_tree ./directives
My routes.js.coffee.erb
#Bento.config ["$routeProvider", ($routeProvider) ->
$routeProvider.when("/",
controller: "ActivitiesController"
templateUrl: "<%= asset_path('templates/user/activities.html.haml') %>"
redirectTo: (current, path, search) ->
if search.goto
"/" + search.goto
else
"/"
).when("/projects/activities",
controller: "ProjectAllActivitiesController"
templateUrl: "<%= asset_path('templates/projects/activities.html') %>"
redirectTo: "/example"
).when("/projects/:id",
controller: "ProjectCtrl"
templateUrl: "<%= asset_path('templates/projects/list.html') %>"
redirectTo: (current, path, search) ->
if search.goto
"/projects/:id" + search.goto
else
"/projects/:id"
).otherwise redirectTo: "/"
]
And lines that I added to my config/routes.rb file
match "api" => proc { [404, {}, ['Invalid API endpoint']] }, via: [:post]
match "api/*path" => proc { [404, {}, ['Invalid API endpoint']] }, via: [:post]
match "/*path" => redirect("/?goto=%{path}"), via: [:post]
Since I'm using rails 4, I need to add a via
# sign is adding whenever I refresh my root path localhost:3000/ but it's not working in nested URLs like localhost:3000/projects/1 it's still reading my routes for RAILS.
PS: Whenever i refresh localhost:3000/projects/activities for example, it's still reading my rails routes instead of going to localhost:3000/example.