ReferenceError: " postIts.forEach(function(postit)" on list.ejs? postIts is not defined at eval (eval at compile - sails.js

I need to loop through an object PostIts and display the "Id", " Title" with an ejs "forEach" Loop Am using sails.js "1.2.3" and mongodb on local host, but i get error
ReferenceError : postIts is not defined at eval (eval at compile ?
Here is the code on the PostItsController.js:
module.exports = {
list: function(req, res) {
// res.view('list');
PostIts.find({}).exec(function(err, postIts) {
if (err) {
res.send(500, { error: 'Database Error' });
}
res.view('list', { postIts: postIts });
});
}
};
And here is the code on list.ejs:
<tbody>
<% postIts.forEach(function(postit){ %>
<tr>
<td>
<%= postit.id %>
</td>
<td>
<%= postit.title %>
</td>
<td></td>
</tr>
<% }) %>
</tbody>
I should get the value of the ID and title displayed on the list.ejs page in a table, but instead I get an error that the postIts object is not defined.

First of all your route '/postIts/list': { view: 'list' }, should point to an action (since it has backend logic) not a view, so in your case "/postIts/list": "PostItsController.list", but if you're using actions2 things would be simpler
Secondly you don't need to tell your users that you have a database error error: "Database Error"
Using Actions2
sails generate action post/list
In your config/route.js
'POST /api/v1/post/list': { action: 'post/list' },
In your action
module.exports = {
friendlyName: "List Posts",
description: "List all post in our site",
inputs: {},
exits: {
success: {
description: "The path to your template file",
viewTemplatePath: "list"
}
},
fn: async function(inputs) {
var posts = await Post.find();
// All done.
return { postIts: posts };
}
};
postit works
An Boohoo! it works
https://sailsjs.com/documentation/concepts/actions-and-controllers/routing-to-actions

If you're sure that res.view('list', { postIts: postIts }); is actually sending the correct data you can use _.each(postIts, cb()) ... instead

For some reason the postIts object didnt save the data from the post req I made instead it just recalled what I posted. and I used the '_.each(postIts, function (postit)' and it finally worked.
to me its like a magic happened hahaha but yeah I learned from it.
thanks #Navicstein Rotciv for the quick replies.

Related

test list of dynamically created table headers using protractor and angular 6

I am using protractor with angular 6. stuck in a situation where i want to write test case to test a list of table headers which are created with data coming from backend called in ngOnInit.
i tried using tick and fakeAsync but keep on getting error
Failed: Cannot read property 'assertPresent' of null
below is my code:
app.po.ts
goToScannersList() {
return browser.get('/scanners');
}
getScannersList() {
let items = element.all(by.css('.scannerlist th')).map(function (elm) {
return elm.getText();
});
return items;
}
If i use spec like in 1) i get error mentioned above even if i remove page.goToScannersList();
but if use spec like in 2) my test is success irrespective of what value it returns.
1)
app.e2e-spec.ts
it('should display list of scanners', fakeAsync(() => {
page.goToScannersList();
tick(4000);
expect(page.getScannersList()).toEqual([
"ScannerID",
"Desc",
"Owner"
]);
}));
2)
app.e2e-spec.ts
it('should display list of scanners', () => {
page.goToScannersList();
fakeAsync(()=>{
tick(4000);
expect(page.getScannersList()).toEqual([
"ScannerID",
"Desc",
"Owner"
]);
})
});
scanners.component.html
<table class="scannerlist" id="scannersList" style="text-align:center;width:100%">
<thead>
<tr ><th *ngFor="let col of scannerKeys">{{col}}</th>
</tr>
</thead>
<tbody>
<tr *ngFor="let row of scannerData">
<td>{{row.ScannerID}}</td>
<td>{{row.Desc}}</td>
<td>{{row.Owner}}</td>
</tr>
</tbody>
</table>
scanners.component.ts
ngOnInit() {
this.scannerService.getScannerDetails().subscribe((data)=>{
this.scannerData = data.Data;
this.scannerKeys = this.getKeys(data.Data[0]);
});
}
let me know if anybody has any idea how to implement it. thanks in anticipation.

How to fetch data from mongodb in MERN

I got a problem while getting information from db to frontend in MEAN Stack.
i've try using axios plugin to fetch data, but nothing show.
this is the code:
and this is my data in mongodb:
how can i show the information to this part (ex: for username)?
<div className="user-details">
<tr>
<th>Username: </th>
<th></th>
</tr>
</div>
I am not sure about what is your problem exactly is, you set user as an array, but in render method you treat as a "text", try to iterate over each user by using map method and show each individual users information, if you have problem getting information from your API, try to set proxy in client-side package.json, to API port, and use actions in reacts ComponentDidMount lifecycle.
You can use like below, Add header to your axios request, set 'crossDomain': true to overcome cors errorr.
export default class Profile extends Component{
constructor(props){
super(props);
this.state = {
users: []
}
}
conmponentDidMount(){
axios.get('/api/account/profile',{ headers: { 'crossDomain': true, 'Content-Type': 'application/json' } })
.then(res=> {
this.setState({ users: res.data }).then(profileState => {
console.log(JSON.stringify(this.state.users))
}); //It sets the state asynchronously
})
}
render(){
<div>
<div className="user-details">
{
this.state.users.map(user =>
<tr>
<td>Username: </td>
<td>{user.name}</td>
</tr>
)
}
</div>
</div>
}
}
thanks,
actually i just used this.state.user.name without maping to show from database
<strong>Name:</strong>{this.state.user.name}<br/>
and in api i get the user id in url to get current user/active user from session.
axios.get('/api/account/profile/info?id=' +id)
.then(res => {
this.setState({ user: res.data.user });
})

Correctly receive data from web API but impossible to display them using Angular2/TypeScript

I'm trying to display the information I receive from a Web API but I think I'm missing something in my component.
The call in the service work (I receive a code 200 with all the Application)
List of the application
But then, I just want to display them in the console and it doesn't fill the table.
ngOnInit(){
this.getApplications();
console.log(this.applications);
}
getApplications() {
this.applications = [];
this._UCCXCiscoService.getApplications().subscribe(
res => {
this.applications = res;
},
error => this.errorMessage = <any>error
);
}
// Model
export interface Application {
self: string;
ScriptApplication: ScriptApplication;
id: string;
applicationName: string;
type: string;
description: string;
maxsession: number;
enabled: string;
}
export interface ScriptApplication {
script: string;
scriptParams: ScriptParam[];
}
export interface ScriptParam {
name: string;
value: string;
type: string;
}
export interface RootObject {
type: string;
application: Application[];
}
My model is good, I'm pretty sure of that. I Think it's the method getApplications() that's wrong, but can't find why...
Thanks in advance for your help,
Florian
EDIT 1 : Code of getApplications() in my service
#Injectable()
export class UCCXCiscoService {
public headers:Headers = new Headers({ 'Content-Type': 'application/json' ,'Authorization': 'Basic User + mdp'});
constructor(private http: Http) {
}
getApplications() {
let options = new RequestOptions({ headers: this.headers });
return this.http.get('API URL', options)
.map(data => <Application[]> data.json().application)
.catch(this.handleError);
}
Yes this method works and returns me the applications (as shown in the picture List of Applications). I didn't put the api url and the password here for privacy reason ^^'
EDIT 2 :
getApplications() of component and the response of the service
EDIT 3 :
<div class="contentPage">
<div class="pageTitleHeaderContainer">
<div class="pageTitle">
<span>Cisco</span>
</div>
</div>
<div class="subContent">
<message-to-user messageToUser={{messageToUser}} messageLevel={{messageLevel}}></message-to-user>
<table class="table table-hover table-condensed">
<th>Id</th>
<th>Nom</th>
<tr *ngFor="#application of applications">
<td>{{application?.id}}</td>
<td>{{application?.applicationName}}</td>
</tr>
</table>
</div>
</div>
Yor are printing on the console in the ngOnInit() method, i.e. before the subscription code is executed and therefore before the applications property is filled.
Move console.log() method inside the arrow function of subscribe() just after this.applications = res;
So thanks to the community, I found my problem. First the console.log() wasn't in the right place. Then I needed to change the ngFor to display the info and now it works fine !
You can read the comment of my post, to find the answer.

angularjs $resource : can't $save JSON

starting with angular, i am trying to GET data from the server and then POST back modifications with $resources.
It's working fine except the "save" function. No Data is POSTed back to the server.
here is the html
<div ng-controller="myCtrl">
<div ng-repeat="obj in objs">
<h2>{{obj.data_1}}</h2>
<h3>{{obj.data_2}}</h3>
<input type='text' ng-model="obj.data_1"><br/>
<textarea ng-model="obj.data_2" required></textarea><br/>
<button ng-click="save()">Save</button>
</div>
</div>
service.js
'use strict';
angular.module('App.services', ['ngResource']).
factory('Obj', function($resource){
return $resource('url/to/json');
});
controller.js:
'use strict';
angular.module('App.controllers', []).
controller('myCtrl', ['$scope', 'Obj', function($scope, Obj) {
$scope.objs = Obj.query();
$scope.save = function() {
$scope.objs.save();
}
}]);
Do you know why nothing is POSTed back when i save ?
Using the query method on the $resource object implies return as follows 'query': {method:'GET', isArray:true} it's mean that your $scope.objs is an array of objects and not an object and depending on number of elements you can use the folowing notation:
$scope.objs[i].save()
where i is the index of element in the array, forexample if you have return like:
[ {id:1, name:'Some name', age:35} ];
then your code : $scope.objs[0].save()
Edit:
I have created a plunk, maybe it will help you... http://plnkr.co/edit/62iPCAUNjV0oJROhul1G
Shouldn't there be another $resource declared for POST the way it is declared for GET? Each $resource specify particular REST service.
//services.js
'use strict';
angular.module('App.services', ['ngResource'])
.factory('GetObj', function($resource){
return $resource('url/to/json');
}
.factory('SaveObj', function($resource){
return $resource('url/to/post');
});
//controller.js
'use strict';
angular.module('App.controllers', []).
controller('myCtrl', ['$scope', 'GetObj', 'SaveObj', function($scope, GetObj, SaveObj) {
$scope.objs = Obj.query();
$scope.save = SaveObj.save(objs, function(resp) {
//Callback
console.log("Response from POST: %j", resp);
}
}]);

knockoutjs mapping select data-bind options

I am having problems binding the selected value of a selectbox to a property within the view model. For some reason it keeps coming back unchanged when posted back to the server.
My Html is:
<form action="/Task/Create" data-bind="submit: save">
<table border="1">
<tr>
<td>ref type</td>
<td><select data-bind="options: ReferenceTypes, optionsText: 'Name', optionsCaption: 'Select...', value:Task.ReferenceTypeId"></select></td>
<td>Reference</td>
<td><input data-bind="value:Task.Reference" /></td>
</tr>
</table>
<button type="submit">Save Listings</button>
</form>
The Javascript is:
<script type="text/javascript">
var viewModel = {};
$.getJSON('/Task/CreateJson', function (result) {
viewModel = ko.mapping.fromJS(result.Data);
viewModel.save = function () {
var data = ko.toJSON(this);
$.ajax({
url: '/Task/Create',
contentType: 'application/json',
type: "POST",
data: data,
dataType: 'json',
success: function (result) {
ko.mapping.updateFromJS(viewModel, result);
}
});
}
ko.applyBindings(viewModel);
});
</script>
JSON from Fiddler that gets loaded into the page as below.
{
"ContentEncoding":null,
"ContentType":null,
"Data":{
"Task":{
"ReferenceTypeId":0,
"Reference":"Default Value"
},
"ReferenceTypes":[
{
"Id":2,
"Name":"A Ref Type"
},
{
"Id":3,
"Name":"B Ref Type"
},
{
"Id":1,
"Name":"C Ref Type"
}
]
},
"JsonRequestBehavior":1
}
This comes back into the server (ASP.NET MVC3) correctly, with the updated Reference string value, but ReferenceTypeId is not bound to the correctly selected drop down value. Do I need to perform any additional functions to bind correctly etc? Or tell the data-bind what the select value column is (Id) etc? I have checked in Fiddler on the values getting posted back from the browser, and it has the same original value (0). So it is definately not the server.
I hope someone can help, if you need any further information please ask.
Kind Regards
Phil
The issue is that your options binding will try to assign the object that it is bound to, to the value observable specified.
For example if you select "A Ref Type" the options binding will push the json object
{ "Id":2, "Name":"A Ref Type" }
Into your Task.ReferenceTypeId observable which will then be serialized back to your server. In this case you need to add an optionsValue config options to tell the binding just to save the id.
<select data-bind="options: ReferenceTypes, optionsText: 'Name',
optionsCaption: 'Select...', optionsValue: 'Id', value:Task.ReferenceTypeId">
</select>
Here's an example.
http://jsfiddle.net/madcapnmckay/Ba5gx/
Hope this helps.