Ember Route Query Params - ember.js

i would like to open a new perspective with query params.
That means in my index.hbs i click a button get the value from the input field.
After that i will open a new route in my case map-view with path '/map' with query params like
localhost:4200/map/?search=xyz
when i do in my index controller:
queryparams:['location'],
location:null,
and in my route
actions:{
search(location){
this.transitionTo('map-view');
}
}
i get on my index url instantly
/?location=xcyxyx
but i want on my map route
localhost:4200/map/?search=xyz

Define search property in index.js controller, use it for queryParams value transitioning to map-view route.
index.hbs
{{input value=search}}
<br />
<button {{action 'transitionToLocation'}}> Search</button>
controllers/index.js - refer transitionToRoute
import Ember from 'ember';
export default Ember.Controller.extend({
search:'india',
actions:{
transitionToLocation(){
this.transitionToRoute('map-view',{queryParams: {search: this.get('search')}});
}
}
});
routes/map-view.js
Define queryParams search with refreshModel true then this will force to fire beforeModel and model and afterModel hook for search property change.
import Ember from 'ember';
export default Ember.Route.extend({
queryParams:{search: {refreshModel:true}},
});

The queryparam is going to be 'search' since that is what you want showing in your URL.
The syntax can be found on:
https://guides.emberjs.com/v2.10.0/routing/query-params/
Further down on that page, it shows how to specify query parameters when using transitionTo. Hope this helps.

Related

How can I avoid "Assertion Failed: `id` passed to `findRecord()` has to be non-empty string or number" when refreshing an ember page?

There's this really annoying feature about Ember that I'm not sure how to get around. I may have a url that looks like the following
http://{my-blog-name}/posts/view/{some-blogpost-ID}
The way I get to this page is by clicking on a link inside of my {my-blog-name}/posts page. This works and will display the page as expected. However, if I try to refresh the page, or if I just literally type my http://{my-blog-name}/posts/view/{some-blogpost-ID} into my url search box, I will get
Assertion Failed: `id` passed to `findRecord()` has to be non-empty string or number
Here is how I navigate to the posts/view/{some-blog-id} page.
post.js
import Ember from 'ember';
export default Ember.Route.extend({
model: function() {
return this.store.findAll('post');
}
});
posts.hbs
<li class="title-list-item">{{#link-to "posts.view" posts}}{{posts.title}}{{/link-to}}</li>
view.js
import Ember from 'ember';
var siteId;
export default Ember.Route.extend({
model(params) {
siteId = params.site_id;
return this.store.findRecord('post', params.site_id);
}
});
view.hbs
<div id="Links">
<h1 id="blog-header-title">My Blog</h1>
<!--<p>{{!#link-to 'welcome'}} See about me{{!/link-to}}</p>-->
{{outlet}}
</div>
{{outlet}}
router.js
import Ember from 'ember';
import config from './config/environment';
const Router = Ember.Router.extend({
location: config.locationType,
rootURL: config.rootURL
});
Router.map(function() {
this.route('index', { path: '/' }); // This is usually automatic if path undeclared, but declared here to support /index below
this.route('posts', function() {
this.route('view', {path: '/view/:post_id'});
});
this.route('welcome');
}
This is really frustrating because it means I can't make a blog post and share the link with a friend. Why does this happen and is there a good way to get around it?
posts.js route is returning all the posts available, that's the RecordArray.
<li class="title-list-item">{{#link-to "posts.view" posts}}{{posts.title}}{{/link-to}}</li>
so in the above posts - refers to single post model or RecordArray of post model ?. if the above is single model then you will receive params.post_id in model hook of view.js, currently you are taking params.site_id instead of params.post_id.
Reason for not executing the model hook.
https://guides.emberjs.com/v2.13.0/routing/specifying-a-routes-model/#toc_dynamic-models
Note: A route with a dynamic segment will always have its model hook
called when it is entered via the URL. If the route is entered through
a transition (e.g. when using the link-to Handlebars helper), and a
model context is provided (second argument to link-to), then the hook
is not executed. If an identifier (such as an id or slug) is provided
instead then the model hook will be executed.

route.afterModel hook not being hit

The afterModel hook is not being hit when you attempt to transitionTo from a parent route to the same route.
I expected the afterModel hook to always fire.
Twiddle
Edit:
It's kind of hard to understand unless you are can look at the twiddle but here's the code
// Controller/application.js
export default Ember.Controller.extend({
appName: 'Ember Twiddle',
actions: {
goTo() {
this.transitionToRoute('food');
}
}
});
// templates/application.hbs
<button onclick={{action 'goTo'}}>Food Options</button>
<br>
{{outlet}}
//router.js
const Router = Ember.Router.extend({
location: 'none',
rootURL: config.rootURL
});
Router.map(function() {
this.route('food', function() {
this.route('options');
this.route('fruits');
this.route('veggies');
});
});
//routes/food.js
export default Ember.Route.extend({
model() {},
afterModel() {
this.transitionTo('food.options');
}
});
Clicking the food options button the first time correctly calls the afterModel in food route. Clicking it the second time does not hit the afterModel.
Refer AlexSpeller Diagonal to see what route structure, templates and route hooks are for a given ember route definition. Its an awesome graphical representation of the route structure.
Question:
I am in a sub route under food, say food/fruits. If I click the button
again I expect to be taken to the food route and then redirected to
options
Answer: food route has no URL, as it is a parent route. You will always be in a child state of this route (e.g. food.index). So when you say transitionTo('food') that means you are transitioning to food.index route.
URL /food/fruits - will execute food model hooks and fruits model hook.
URL /food - will execute food/index model hook and it will not execute food model hook.
So in your case, You can remove this.transitionTo('food.options') from food afterModel hook and you can introduce food.index route which has food options.
Look at modified ember twiddle which includes index route.

how to bind Application controller property in another controller ember

i have search property in ApplicationController and its linked with input field of searching.
i want to access search field of ApplicationController in ProjectController. it should be sync.
i use following code but its not working.
/ app/controllers/projects/index.js (project Controller)
import Ember from 'ember';
export default Ember.Controller.extend({
needs: ['application'],
searchBinding: 'controllers.application.search'
});
/ app/controllers/application.js (Application Controller)
import Ember from 'ember';
export default Ember.Controller.extend({
search: ''
)}
application.hbs
{{input value = search}}
Ember needs is deprecated and is now used differently.
It works like this:
applicationController: Ember.inject.controller('application'),
mySearch: Ember.computed.alias('applicationController.search')
In your hbs template -
{{mySearch}}
 is in sync with applications property "search".
You can access any controller within controller by inject it.
import Ember from 'ember';
export default Ember.Controller.extend({
applicationController: Ember.inject.controller('application'),
searchProperty: Ember.computed.alias('applicationController.search'),
)};
Managing Dependences between Ember controllers
You can access controllers properties included with needs this way :
{{controllers.neededController.property}}
In you case try :
{{input value=controllers.application.search}}
See example here : http://jsfiddle.net/6Evrq/

Why is Firebase data not displaying properly in my Ember CLI generated output?

I've successfully setup Ember CLI and Firebase and I'm attempting to bring some basic data into my templates. My 'title' and 'subtitle' data are apparent in the Ember Inspector, as well as my Firebase project dashboard. However, {{foo.title}} and {{foo.subtitle}} are coming back empty and undefined in the browser. Why is that? Here's my code:
application.js (adapter)
import DS from 'ember-data';
export default DS.FirebaseAdapter.extend({
firebase: new window.Firebase('https://<firebase-database-name>.firebaseio.com/')
});
foo.js (model)
import DS from 'ember-data';
export default DS.Model.extend({
title: DS.attr('string'),
subtitle: DS.attr('string')
});
index.js (controller)
import Ember from 'ember';
export default Ember.Controller.extend({
model: function() {
var titles = this.store.createRecord('foo', {
title: 'Title',
subtitle: 'Subtitle'
});
titles.save();
}
});
index.js (route)
import Ember from 'ember';
export default Ember.Route.extend({
model: function() {
return this.store.findAll('foo');
}
});
application.hbs (template)
<h2 id='title'>{{foo.title}}</h2>
{{outlet}}
index.hbs (template)
<h1>{{foo.title}}</h1>
<h3>{{foo.subtitle}}</h3>
The title and subtitle fail to display in the templates.
The Ember Inspector View Tree tab shows 'index' with 'DS.RecordArray:ember368' for the model.
The Ember Inspector Data tab shows Model Type of 'foo' with # Records of 1. When I click on that record, it displays the Firebase ID, title, and subtitle values. When I inspect my Firebase data url, I see the following structure:
firebase-database-name
|— foos
|— JU1Ay8emCNNZBeqYoda
|— subtitle: "Subtitle"
|— title: "Title"
Seems like everything is correct, but the templates do not display the data values. Thanks for any help.
The answer to this question centers on properly retrieving and exposing Ember Data, and not so much to do with Firebase or Ember CLI. There are multiple issues with the code above…
The foo.js code represents a simple model, and is written correctly.
The index.js route is implemented correctly. It is retrieving and returning the ‘foo’ model from the Ember Data store as an array, which, via EmberFire and the Firebase adapter, is ultimately being pulled from the Firebase database. However, this is part 1 of 3 problems. If you want this data displayed once across the application, dispense with the index.js route, and just define an application.js route, like this:
import Ember from 'ember';
export default Ember.Route.extend({
model: function() {
return this.store.findAll('foo');
}
}
The index.js controller has a number of issues, and is part 2 of 3 problems. Firstly, controllers do not have a ‘model’ method, they only have a ‘model’ property (Ember Routes are the ones that employ a ‘model’ method, and can also set the ‘model’ property of a controller via a Route’s ‘setupController’ method). Secondly, instead of Ember.Controller, it needs to extend Ember.ObjectController for a singular data instance, or, Ember.ArrayController for an array of data, which is the controller needed here, since ‘this.store.findAll(“foo”)’ in the index.js route is going to return an array of objects. Controllers are not used to save or retrieve data from a server, but they can be used to decorate a model. Given that the route is returning the model, the controller, in this simple data exercise, is not even necessary.
The application.hbs handlebars template is part 3 of 3 problems. It is not setup to properly display the model that is being provided to it via the route. It’s necessary to employ the {{#each}} helper, to loop over the data array that is being returned via the route’s model method. Try this:
{{!-- looping over the 'foo' model returned via the route --}}
{{#each foo in model}}
<h2>Application Title = <span style="color: blue;">{{foo.title}}</span></h2>
<h4>Application Tagline = <span style="color: blue;">{{foo.tagline}}</span></h4>
{{/each}}
{{outlet}}
The index.hbs handlebars template is not necessary. The application.hbs template is sufficient to display the data of interest.
This is a very basic exercise, but illustrates fundamental aspects of using Ember Data properly.

Can we route from a component in ember js?

I have a component which has a button with an action like
{{action 'create'}}
and inside the action create i wrote like this.transitionTo('page.new');
But i am getting an exception like Cannot read property 'enter' of undefined can anyone answer please?Just want to know is that possible to route from a component?
The way to do that is to use this.sendAction() from your component and bubble it up to the router. The router can then call this.transitionTo().
The way link-to does it is by injecting routing _routing: inject.service('-routing'),
https://github.com/emberjs/ember.js/blob/v2.1.0/packages/ember-routing-views/lib/components/link-to.js#L530
Ember.Component is extended from Ember.View and you cant use this.transitionTo in a view. It can be done only through a controller/router.
If you want a transition inside the component on clicking, you could use the link-to helper, but if you still want to be able to handle that action, read: http://emberjs.com/guides/components/handling-user-interaction-with-actions/ and the guide after it.
I found out the answer it is possible.we can use simply use the following code from our components action
App.Router.router.transitionTo('new route');
and we will get a call back for this,in which we can set the new route's model.Use the following code for that.
App.Router.router.transitionTo('your route here').then(function(newRoute){
newRoute.currentModel.set('property','value');
});
Injection is the last thing you wanna do. The way you communicate actions between routes and components is to use the sendAction Method Send Action
template.hbs
{{your-component action="nameOfYourRouteAction" }}
route.js
export default Ember.Route.extend({
ratesService: Ember.inject.service(),
model() {
//return yourdata
},
actions: {
nameOfYourRouteAction(...args){
this.transitionTo(...args);
}
}
});
in your component.js
import Ember from 'ember';
export default Ember.Component.extend({
actions: {
toggleTransition: function(...args) {
this.sendAction('action', ...args);
}
}
});
component.hbs
<button {{action "toggleTransition" 'your route'}}>Change Route</button>