can't retrieve data from OdooRPc - javascript

I am trying to retrieve data from the database using jsonRpc using odoo api but i got the erro like "HTTP/1.1 GET /projects" - 404 Not Found"
here is my code snnipet
python script which is used to manipulate the data
class projects:
def GET(self):
print("get")
data=[]
web.header('Access-Control-Allow-Origin', '*')
web.header('Access-Control-Allow-Credentials', 'true')
web.header('Content-Type', 'application/json')
auth = web.input()
print(auth)
odoo = odoorpc.ODOO('field.holisticbs.com',port=8069)
odoo.login('field.holisticbs.com','info#holisticbs.com','admin')
Project = odoo.execute('project.task','search_read',[[['company_id', '=', int(auth.company)],['user_id','=',int(auth.user)]]])
return json.dumps(Project)
controller.js
controller('projectCtrl',function ($scope,API,$localStorage,localStorageService) {
// body...
console.log("Project ctrl");
API.showLoad();
var resource = "projects";
API.getData(resource, localStorageService.get('user')).then(function(data) {
// console.log("quotation"+data);
console.log(data);
$scope.projects = data;
}).catch(function(data, status) {
alert("error in request");
//console.error('GET Orders error', response.status, response.data);
}).finally(function() {
console.log("finally finished projects");
API.hideLoad();
});
})
service.js
function getDetails(resource,data) {
console.log(resource);
console.log(data);
var request = $http({
method: "get",
url: backend+resource,
params: {instance: data.inst, user:data.user, company:data.company}
});
return(request.then( handleSuccess, handleError ));
}
project.html(view page which display blank)
<ion-view view-title="Projects">
<ion-content>
<ion-list>
<div class="card" ng-contoller="projectCtrl">
<a class="button button-icon" href="#/app/newProject">
<button class="button button-positive">Create Project</button> </a>
<h2> project </h2>
<ion-item ng-repeat="proj in projects" href="#/app/projects/{{proj.id}}">
<h2 class="padding">{{proj.id}}. {{proj.name}}</h2>
<div class="row" ng-if="proj.partner_id[1]">
<span class="col col-25">Customer:</span>
<span class="col">{{proj.partner_id[1]}}</span>
</div>
<div class="row" ng-if="quot.date_order">
<span class="col col-25">Date:</span>
<span class="col">{{proj.date_order}}</span>
</div>
<div class="row" ng-if="quot.state">
<span class="col col-25">Status:</span>
<span class="col">{{proj.state}}</span>
</div>
</ion-item>
</div>
</ion-list>
</ion-content>
</ion-view>

just a silly mistake annoying me. not specified in url for routing
urls = (
'/products', 'products',
'/projects', 'projects',
'/product/(.+)', 'product'
)

Related

How to call an API on expansion of a collapsible div and fill its content with the API response using AngularJS?

I am using angularjs 1.6 and I am quite new to it. I have this piece of html below
<span ng-repeat="topdata in userData">
<span style="white-space: pre;">
<a class="collapsed" data-target="#testThis" data-toggle='collapse' ng-click="getInfo(topdata.user_id)">
<pre><i class='fa fa-plus'></i><span>Some text</span> </pre>
</a>
</span>
<div id="testThis" class='collapse'>
<!-- API content goes here -->
</div>
</span>
In the js part
$scope.getInfo = function(user_id) {
toSend = {"user_id": user_id}
$http({
method: 'POST',
url: /some-url,
data: toSend,
}).then(function(response) {
// fill the response data inside #testThis div
})
}
Currently when the user clicks on the collapsible span, it expands and a function is called that calls an API. But I don't know how to fill the response of the API inside the content of the expanded span.
Any idea how this can be done?
You can assign the response to the userData and bind the collapsed element to it.
For example
<div id="testThis" class='collapse' ng-bind="userData.more"></div>
and
}).then(function(response) {
const userData = $scope.userData.find(data => data.user_id === user_id);
userData.more = response;
});
Here is a live example (I did some necessary changes to make it work but the idea is the same).
angular.module('app', []).controller('ctrl', function($scope, $http) {
$scope.userData = [{
user_id: 8
}];
$scope.getInfo = function(user_id) {
toSend = {
"user_id": user_id
}
$http({
method: 'GET',
url: 'https://jsonplaceholder.typicode.com/todos/1',
//data: toSend,
}).then(function(response) {
const userData = $scope.userData.find(data => data.user_id === user_id);
userData.more = response;
})
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.7.5/angular.min.js"></script>
<div ng-app="app" ng-controller="ctrl">
<span ng-repeat="topdata in userData">
<span style="white-space: pre">
<a
class="collapsed"
data-target="#testThis"
data-toggle="collapse"
ng-click="getInfo(topdata.user_id)"
>
<pre><i class='fa fa-plus'></i><span>Some text</span></pre>
</a>
</span>
<div id="testThis" class="collapse" ng-bind="topdata.more | json">
<!-- API content goes here -->
</div>
</span>
</div>

data parsing not working in angularjs

I have tried to parse my JSON data to angular js app but parsing is not working on my wamp server.
When I click the submit button on login page, there is no response. Please advise where I made mistake in my code.
Controller.js:
var app = angular.module("empApp", []);
app.controller("emp", ['$scope', 'empService', function($scope, empService){
$scope.doSearch = function(){
empService.findEmployeeById($scope.searchEmpno, function(r){
$scope.empno = r.empno;
$scope.ename = r.ename;
$scope.edept = r.edept;
$scope.esal = r.esal;
});
};
}]);
app.service("empService", ['$http', '$log', function($http, $log){
this.findEmployeeById = function(empno, cb){
$http({
url: 'http://localhost/',
method: 'GET'
})
.then(function(resp){
cb(resp.data);
}, function(resp){
$log.error('Error occurred');
});
};
}
}]);
app.directive('empDetails', function(){
return {
templateUrl: 'emp-details.html'
}
});
HTML
<body ng-app="empApp">
<div class="container-fluid">
<div ng-controller="emp">
<form class="form-inline">
<div class="form-group">
<label>Enter Employee No:</label>
<input type="text" name="name" class="form-control" ng-model="searchEmpno"/>
</div>
<div>
<button type="button" class="btn btn-primary" ng-click="doSearch()">Click</button>
</div>
</form>
<hr>
<div emp-details ng-if="empno != undefined">
</div>
</div>
</div>
</body>
emp-details.html
<div class="panel panel-primary">
<div class="panel-heading">
<h3>Employee details</h3>
</div>
<div class="panel-body">
<div class="row">
<div class="col-sm-4"><strong>Employee No</strong></div>
<div class="col-sm-7">{{empno}}</div>
</div>
<div class="row">
<div class="col-sm-4"><strong>Name:</strong></div>
<div class="col-sm-7">{{ename}}</div>
</div>
<div class="row">
<div class="col-sm-4"><strong>Department:</strong></div>
<div class="col-sm-7">{{edept}}</div>
</div>
</div>
</div>
JSON:
{
"employee":{ "empno": 251, "name":"John", "age":30, "edept":"New York" }
}
Most of the issues are related to project structure and file organization.
I would recommend reading johnpapa-angular-styleguide for properly organizing and coding an angularJS application.
There are multiple changes needed.
You're not referencing your Controller.js file.
There is an additional } is there in your service
There is no file like data.json. You will need to create that file and reference it in your service.
$http({
url: 'data.json',
method: 'GET'
})
In your service you are returning resp.data. It should be resp.data.employee.
cb(resp.data.employee);
When you are referencing paths you should use relative URL.
See the working plnkr
Couple of this:
Change your URL from 'http://localhost/' to 'data.json'
In the callback, change resp.data to resp.data.employee. This will make sure you directly get access to the employee data.
Let me know if this helps.
Controller.js
$scope.doSearch = function(employeeN){
empService.findEmployeeById(employeeN)
.then(function(r){
$scope.empno = r.empno;
$scope.ename = r.ename;
$scope.edept = r.edept;
$scope.esal = r.esal;
});
};
Service
this.findEmployeeById = function(empno){
$http({
url: 'http://localhost/data.json',
method: 'GET'
})
.then(function(resp){
return resp.data.employee;
}, function(resp){
$log.error('Error occurred');
});
};
HTML
<div>
<button type="button" class="btn btn-primary" ng-click="doSearch(searchEmpno)">Click</button>
</div>

nested ng-repeat with json and rest api call back

I am trying to make a UI using list of product in a json(products.json) file on local and their availability in number from wp rest api call back in html(ionic) I have this:
Controller:
.controller('ShopCtrl', function($scope, $ionicActionSheet, BackendService, CartService, $http, $sce ) {
$scope.siteCategories = [];
$scope.cart = CartService.loadCart();
$scope.doRefresh = function(){
BackendService.getProducts()
.success(function(newItems) {
$scope.products = newItems;
console.log($scope.products);
})
.finally(function() {
// Stop the ion-refresher from spinning (not needed in this view)
$scope.$broadcast('scroll.refreshComplete');
});
};
$http.get("http://example.com/wp-json/wp/v2/categories/").then(
function(returnedData){
$scope.siteCategories = returnedData.data;
console.log($scope.siteCategories);
}, function(err){
console.log(err);
});
Template view:
<div ng-repeat = "product in products">
<div class="item item-image" style="position:relative;">
<img ng-src="{{product.image}}">
<div ng-repeat = "siteCategory in siteCategories">-->
<button class="button button-positive product-price" ng-click="addProduct(product)">
<p class="white-color product-price-price">post <b>{{siteCategory[$index].count}}</b></p>
</button>
</div>
</div>
<div class="item ui-gradient-deepblue">
<h2 class="title white-color sans-pro-light">{{product.title}} </h2>
</div>
<div class="item item-body">
{{product.description}}
</div>
</div>
so how can I achieve that? I tried to use nested ng-repeat but it didn't work out.

Ionic save input as variable

I am coding a weather app with open weather and I would like to save the city (the input) as a variable to call it on another view. So I would like to type in Vienna, send it to result.html and post there the current weather and to check which clothes I should wear, e.g. if the emperature is under 20° the app should say that I should wear a jacket.
Here is my home.html:
<ion-view title="" hide-nav-bar="true" hide-back-button="true">
<ion-content>
<div class="list card">
<div class="item item-avatar">
<img src="img/appicon.png">
<h2>Weather App</h2>
<p>What clothes do you need?</p>
</div>
</div>
<div class="list">
<div class="item item-input-inset">
<label class="item-input-wrapper">
<input type="text" placeholder="City" ng-model="inputs.city">
</label>
<input class="button button-small" type="submit" ng-click="saveText(inputs)" value="Save" ng-controller="WeatherCtrl" />
</div>
</div>
</ion-content>
</ion-view>
Here my app.js:
angular.module('starter', ['ionic'])
.run(function($ionicPlatform) {
$ionicPlatform.ready(function() {
if(window.cordova && window.cordova.plugins.Keyboard) {
cordova.plugins.Keyboard.hideKeyboardAccessoryBar(true);
cordova.plugins.Keyboard.disableScroll(true);
}
if(window.StatusBar) {
StatusBar.styleDefault();
}
});
})
.config(function ($stateProvider, $urlRouterProvider) {
$stateProvider
.state('home', {
url: '/home',
controller: 'HomeCtrl',
templateUrl: 'views/home.html'
})
.state('result', {
url: '/result',
controller: 'WeatherCtrl',
templateUrl: 'views/result.html'
});
$urlRouterProvider.otherwise('/home');
})
.controller('HomeCtrl', function($scope) {
$scope.forcastDisabled = true
})
.controller('WeatherCtrl', function ($scope, $http, $ionicLoading, $location) {
var directions = ['N', 'NE', 'E', 'SE', 'S', 'SW', 'W', 'NW'];
$scope.getIconUrl = function(iconId) {
return 'http://openweathermap.org/img/w/' + iconId + '.png';
};
$scope.save = {};
$ionicLoading.show();
$scope.saveText = function (inputs) {
alert('Geht');
$location.path('result');
$scope.save = angular.copy(inputs);
$scope.inputs.city;
}
var vm = this;
// Vienna
var id = 2761369;
var city = 'Vienna';
var URL = 'http://api.openweathermap.org/data/2.5/weather?q=' + city;
var request = {
method: 'GET',
url: URL,
params: {
q: city,
mode: 'json',
units: 'imperial',
cnt: '7',
appid: '938c0cf5969f353bc718735f59aeffd6'
}
};
$http(request)
.then(function(response) {
vm.data = response.data;
$scope.weather = response.data;
}).
catch(function(response) {
vm.data = response.data;
$scope.weather = response.data;
});
$ionicLoading.hide();
});
And last my result.html:
<ion-view view-title="Current Weather">
<ion-content>
<div class="list card">
<div class="item item-divider"><h1>City: {{weather.name}}</h1></div>
<div class="item item-thumbnail-left">
<img src="{{getIconUrl(weather.weather[0].icon)}}" />
<h1>{{weather.weather[0].main}}</h1>
</div>
<div class="item item-icon-left">
<i class="icon ion-thermometer"></i>
<h2>Current Temperature: {{weather.main.temp}}°</h2>
</div>
<div class="item item-icon-left">
<i class="icon ion-thermometer"></i>
<h2>Today's High: {{weather.main.temp_max}}°</h2>
</div>
<div class="item item-icon-left">
<i class="icon ion-thermometer"></i>
<h2>Today's Low: {{weather.main.temp_min}}°</h2>
</div>
<div class="item item-icon-left">
<i class="icon ion-waterdrop"></i>
<h2>Humidity: {{weather.main.humidity}}%</h2>
</div>
<div class="item item-icon-left">
<i class="icon ion-shuffle"></i>
<h2>Wind: {{weather.wind.speed}}mph, {{getDirection(weather.wind.deg)}}</h2>
</div>
</div>
</ion-content>
</ion-view>
I know I am not currently using the input, because I do not know how to do this in js. So how can I call my input in the url and then in the request?
Thanks in advance!
Try to:
Add the city variable as a parameter to your state definition:
.state('result', {
url: '/result',
controller: 'WeatherCtrl',
templateUrl: 'views/result.html',
params: {
city: null
}
})
Pass the variable to the target state:
$state.go("result", {city: inputs.city});
Inject the $stateParams service and use the variable in the controller:
var city = $stateParams.city;
See https://github.com/angular-ui/ui-router/wiki/URL-Routing for more details.
EDIT
Check out this plunker demonstrating my changes: https://plnkr.co/edit/3dvhPCjv24Lebduy8BZz
Note that I moved the saveText() function to the HomeCtrl and removed the ng-controller directive from your home.html.

How to display individual blog post by its ID in Angular/Express/MongoDB app

I can't figure out how to get a single blog post by its ID -- I'm very new to this.
So far my main blog app has an ng-repeat which can get all posts. What I want is to be able to click on the name of the post and be show only that post and nothing else -- eventually I want to be able to delete and edit by ID as well.
I know filters exist, but I am not sure how to have a filter enabled by clicking, or how to make sure that when I click it, it will filter by that _id.
My 'post.html' looks as follows -
<div ng-controller="PostController" class="panel panel-default">
<div class="panel-heading">
<h3 class="panel-title">
<strong>
<a href ng-click="selectTab('viewPost')">{{post.title}}</a>
</strong> created on {{post.time | date: 'MM/dd/yy # h:mma'}}
</h3>
</div>
<div class="panel-body">
{{post.body}} <br>
{{post._id}}
</div>
</div>
At the moment I have the ng-click directive set up to show this-
<div ng-show="isSelected('viewPost')">
<view-post></view-post>
</div>
Which is a custom directive linking this file --
<div class="panel panel-default">
<div class="panel-heading">
<h3 class="panel-title">
<strong>
<a href>{{postById.title}}</a>
</strong> created on {{postById.time | date: 'MM/dd/yy # h:mma'}}
</h3>
</div>
<div class="panel-body">
{{postById.body}}
</div>
</div>
When that template is shown, the expressions are missing altogether.
I have a getPost function in my controller 'PostController' but I'm not sure how to use it.
$scope.getPost = function () {
$http({method: 'GET', url: '/api/blog/:post_id', data: $scope.postById})
.then(function(response){
//your code in case the post succeeds
console.log(response);
})
.catch(function(err){
//your code in case your post fails
console.log(err);
});
}
My API works using Postman, as I can get/update/delete posts on that route. At the moment I have nothing going on in the address bar, no routes in particular -- everything is based around custom directives displaying the templates I want when clicked.
I had thought it could be a problem with the scope of my controllers.
A snippet of my HTML might make it more apparent--
<body ng-controller="PanelController">
<div class="site-wrapper">
<div class="site-wrapper-inner">
<div class="cover-container">
<div class="masthead clearfix">
<div class="inner">
<nav-bar></nav-bar>
</div>
<div ng-controller="PostController">
<div ng-show="isSelected('blog')">
<div ng-repeat="post in posts | orderBy: 'time':true">
<blog-post></blog-post>
</div>
</div>
<div ng-show="isSelected('about')">
<about-page></about-page>
</div>
<div ng-show="isSelected('contact')">
<contact></contact>
</div>
<div ng-show="isSelected('createPost')">
<create-post></create-post>
</div>
<div ng-show="isSelected('viewPost')">
<view-post></view-post>
</div>
</div>
</div>
Hopefully this makes some sense to someone. Any help is appreciated.
EDIT: Just to make it a bit more complete, here's the API for getting posts by ID -
router.route('/blog/:post_id')
.get(function(req, res) {
Post.findById(req.params.post_id, function(err, post) {
if (err) {
res.send(err);
} else {
res.json(post);
}
});
})
.put(function(req, res) {
Post.findById(req.params.post_id, function(err, post) {
if (err) {
res.send(err);
} else {
post.title = req.body.title;
post.body = req.body.body;
}
post.save(function(err) {
if (err) {
res.send(err);
} else {
res.json({ message: 'Post updated!' });
}
});
});
})
.delete(function(req, res) {
Post.remove({
_id: req.params.post_id
}, function(err, post) {
if (err) {
res.send(err);
} else {
res.json({ message: 'Successfully deleted' });
}
});
});
You need to assign your response data to $scope.post It would look something like this...
$http(...).then(function(response) {
$scope.post = response.post;
});

Categories