How to Filter Data in Grid when Route Changed - node.js

Hi I'm very new to angular.
I have an url like http://localhost:3000/prizes/brand1 , brand2, brand3
I want to reload my grid items and filter them base on that brand.
{ path: 'prizes/:brand_name', component: PrizeComponent }
This is the method that I have to get the items
getPrizes() {
return this._http.get('/prizes')
.map(data => data.json()).toPromise()
}
Question
How do I reload/call back the get method base on the new route and how do I get the brand name and pass that one as a parameter to the get method.
Regards

If to use dataService to fetch data:
#Injectable()
export class daraService {
private brandName: string = '';
constructor(aroute: ActivatedRoute) {
aroute.url.subscribe((data) => {
console.log('params ', data); //check for brand here
this.brandName = data[data.length - 1]
});
}
getPrizes() {
// you can access this.brandName value here
return this._http.get('/prizes')
.map(data => data.json()).toPromise()
}
}

Related

Flutter : GetX Variable initialise problem in Profile Data

I am using GetX statemangement on my flutter app. I want to fetch User's Profile data from server. That's Why I create a Profile Model Class and a Controller Screen. But I can't. Here is a problem to initialisation.
json Response -
{
"riderId": 1,
"riderName": "Ramiz Miah",
"riderContact": "01787656565",
"riderEmail": "ramiz#hotmail.com",
"riderImgRef": ""
}
Profile Model
class ProfileModel {
int? riderId;
String? riderName;
String? riderContact;
String? riderEmail;
String? riderImgRef;
ProfileModel(
{this.riderId,
this.riderName,
this.riderContact,
this.riderEmail,
this.riderImgRef});
ProfileModel.fromJson(Map<String, dynamic> json) {
riderId = json['riderId'];
riderName = json['riderName'];
riderContact = json['riderContact'];
riderEmail = json['riderEmail'];
riderImgRef = json['riderImgRef'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = <String, dynamic>{};
data['riderId'] = riderId;
data['riderName'] = riderName;
data['riderContact'] = riderContact;
data['riderEmail'] = riderEmail;
data['riderImgRef'] = riderImgRef;
return data;
}
}
Controller
class ParofileController extends GetxController {
RxMap<String, dynamic> profileDetails = <String, dynamic>{}.obs;
//<============= Fetch and Assign DashBoard Today Details List
void fetchandAssignProfileDetails() async {
try {
ProfileApiService().getProfileDetails().then((resp) {
profileDetails.value = resp;
}, onError: (err) {
debugPrint(err.toString());
});
} catch (e) {
debugPrint(e.toString());
}
}
}
And API Service
class ProfileApiService extends GetConnect {
Future<ProfileModel?> getProfileDetails() async {
Uri url = Uri.parse("${AppConfig.baseUrl}/Rider/GetRiderDetails");
var response = await http.get(
url,
);
if (response.statusCode == 200) {
return ProfileModel.fromJson(jsonDecode(response.body));
} else {
throw Exception('Failed to load User Profile');
}
}
}
And Now my Question is How to Define this variable here ( RxMap<String, dynamic> profileDetails = <String, dynamic>{}.obs; ), that's why it's work properly
I solved this
Rx<ProfileModel?> profile = ProfileModel().obs;
thanks.

Hide payment method if specific shipping method selected in odoo eCommerce website

I want to hide specific payment method (cash on delivery) if specific shipping method selected before. For example, if I check shipping method A , then in the next step, payment methods I have only one method to check ( other methods disabled or unable to check). I try to edit and add many2many relational field of payment.acquirer model in shdelivery.carrier and use this filed in controller but it not work , so far I havent' find the solution.
this is my code snapshot:
my python code:
class ShippingMethod(models.Model):
_inherit = 'delivery.carrier'
payment_acquirer_ids = fields.Many2many('payment.acquirer',string='Payment Mathods')
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
my controller
class WebsiteSaleDeliveryExtraCost(WebsiteSale):
#http.route(['/shop/change_shipping_method'], type='json', auth='public', methods=['POST'], website=True, csrf=False)
def change_shipping_method(self, **post):
carrier_id = post.get('carrier_id')
print('******00******', request.session)
carrier = request.env['delivery.carrier'].browse(int(carrier_id))
acquirer_ids = carrier.payment_acquirer_ids.ids
acquirers = request.env['payment.acquirer'].search([('id','in',acquirer_ids)])
# if acquirers:
# return request.redirect("/shop/payment")
return acquirers.ids
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
her is JavaScript code to route controller:
odoo.define('website_sale_delivery_extra_cost.checkout', function (require) {
'use strict';
var core = require('web.core');
var publicWidget = require('web.public.widget');
require('website_sale_delivery.checkout')
var _t = core._t;
// hide payment method base on shipping method
publicWidget.registry.websiteSaleDelivery.include({
selector: '.oe_website_sale',
events: {
'click #delivery_carrier .o_delivery_carrier_select': '_change_shipping_method',
},
_change_shipping_method: function (ev) {
var self = this;
var $radio = $(ev.currentTarget).find('input[type="radio"]');
if ($radio.val()){
this._rpc({
route: '/shop/change_shipping_method',
params: {
carrier_id: $radio.val(),
}}).then(function (data) {
if (data.length >= 1) {
console.log(data[0]);
console.log('---------');
return { location.reload(); };
} else {
return false;
}
}); // end of then
} //end of if
},
/**
* #private
*/
_trackGA: function () {
var websiteGA = window.ga || function () {};
websiteGA.apply(this, arguments);
},
/**
* #private
*/
_vpv: function (page) { //virtual page view
this._trackGA('send', 'pageview', {
'page': page,
'title': document.title,
});
},
});
});
Any other ideas how to solve this issue ?

undefined is not iterable (cannot read property Symbol(Symbol.iterator))

I'm trying to loop through a fileList in order to perform a delete query. First i fetched data from table "files" in database where attribute "postnumber"=user input. Then it is saved into the "fileList:Files[]". Then a loop through this fileList in order to perform a delete query. but it keeps saying that
"ERROR TypeError: undefined is not iterable (cannot read property
Symbol(Symbol.iterator))". See this image =>
forum-admin-list.component.ts
import { FileService } from 'src/app/shared/file.service';
import { Files } from 'src/app/shared/files.model';
export class ForumAdminListComponent {
fileList:Files[];
onDelete(pNo:string){
this.fservice.getPost(pNo).subscribe(actionArray => {
this.fileList = actionArray.map(item => {
return {
id: item.payload.doc.id,
...item.payload.doc.data()
} as Files;
})
});
for(let i of this.fileList){
this.storage.storage.refFromURL(i.path).delete();
this.firestore.doc("files/"+i.id).delete();
}
}
}
files.model.ts
export class Files {
id:string;
pNo:string;
downloadURL:string;
path:string;
}
file.service.ts
export class FileService {
formData: Files;
constructor(private firestore: AngularFirestore) { }
getPost(userRef){
return this.firestore.collection('files',ref=>ref.where('pNo','==',userRef)).snapshotChanges();
}
}
You're looping through the fileList outside the subscribe(), meaning it won't actually wait for the Observable to be resolved. Try to loop inside your subscribe().
onDelete(pNo:string){
this.fservice.getPost(pNo).subscribe(actionArray => {
this.fileList = actionArray.map(item => {
return {
id: item.payload.doc.id,
...item.payload.doc.data()
} as Files[];
for(let i of this.fileList){
this.storage.storage.refFromURL(i.path).delete();
this.firestore.doc("files/"+i.id).delete();
}
})
});
}
Also you might wanna mark the result of the subscription as Files[] instead of as File

URL to code in node.js applications

I see they use this kind of code to call restful URLs.
Let's say we have /users/{userId}/tasks to create task for a user.
To call this they create another class instead of calling request directly as shown below:
MyAPP.prototype.users = function (userId) {
return {
tasks: function (taskId) {
return this.usersTasks(userId, taskId);
}
}
}
MyAPP.prototype.usersTasks = function (userId, taskId) {
return {
create: function (task, cb) {
make request POST call
}
}
}
Then we can call this as myapp.users('123').tasks().create(task, cb);
What is this kind of coding called and is there any way to automatically generate the code from the URL structure itself?
That is a way of making classes, but I suggest you look into ES6 classes
Defining a class :
class MyAPP {
//:called when created
constructor(name) {
this.name = name;
console.log("[created] MyAPP :",name);
//(a in memory database stored in MyAPP : for example purpose)
this.DB = {'user000':{'tasks':{'task000':'do pizza'},{'task001':'code some magik'}}}
}
//: Get specific taskID for userID
getTask(userID, taskID) {
console.log("[get task]",taskID,"[from user]",userID)
return (this.DB[userID][taskID])
}
//: Get all tasks for userID
allTasks(userID) {
console.log("[get all tasks from user]",userID)
return (this.DB[userID].tasks)
}
//: Create a taskID with taskContent for userID
newTask(userID, taskID, taskContent) {
this.DB[userID].tasks[taskID] = taskContent
}
}
Creating a MyAPP instance :
var myapp = new MyAPP('Pizza API'); //creates a MyAPP with a name
And then (maybe I got your question wrong) using express you would make a server and listen for requests (GET, POST, PUT, ...)
app.get("/APIv1/:userID/:actionID", function(req, res) {
switch(req.params.actionID){
case 'all':
res.send(myapp.allTasks(req.params.userID));
break
default :
res.send("The "+myapp.name+" doesn't support that (yet)")
break
}
});

How to define different context menus for different objects in autodesk forge

I want to define different context menus for different objects in forge viewer,this is my code
viewer.addEventListener(Autodesk.Viewing.AGGREGATE_SELECTION_CHANGED_EVENT,function(e){
if(viewer.getSelection().length==0){return;}
var selectId=viewer.getSelection()[0];
viewer.search("Cabinet",function(ids){
if(ids.indexOf(selectId)!=-1){
viewer.registerContextMenuCallback('CabinetMsg', function (menu, status) {
if (status.hasSelected) {
menu.push({
title: "CabinetMsg",
target: function () {
openLayer('CabinetMsg','954','775','CabinetMsg.html')
}
});
}
});
}else{
viewer.registerContextMenuCallback('CabinetMsg', function (menu, status) {
if (status.hasSelected) {
menu.forEach(function(el,index){
if(el.title=="CabinetMsg"){
menu.splice(menu.indexOf(index),1)
}
})
}
});
}
})
});
But push elements to the array is always later than the context menus show. My custom context menu is always show when I select another object. What I can do?
The codes you provided will create 2 new sub items to the context menu. Here is a way for this case, i.e. you have to write your own ViewerObjectContextMenu. In addition, you need do hitTest in ViewerObjectContextMenu.buildMenu to get dbId selected by the mouse right clicking. Here is the example for you:
class MyContextMenu extends Autodesk.Viewing.Extensions.ViewerObjectContextMenu {
constructor( viewer ) {
super( viewer );
}
isCabinet( dbId ) {
// Your logic for determining if selected element is cabinet or not.
return false;
}
buildMenu( event, status ) {
const menu = super.buildMenu( event, status );
const viewport = this.viewer.container.getBoundingClientRect();
const canvasX = event.clientX - viewport.left;
const canvasY = event.clientY - viewport.top;
const result = that.viewer.impl.hitTest(canvasX, canvasY, false);
if( !result || !result.dbId ) return menu;
if( status.hasSelected && this.isCabinet( result.dbId ) ) {
menu.push({
title: 'CabinetMsg',
target: function () {
openLayer( 'CabinetMsg', '954', '775', 'CabinetMsg.html' );
}
});
}
return menu;
}
}
After this, you could write an extension to replace default viewer context menu with your own menu. Here also is the example:
class MyContextMenuExtension extends Autodesk.Viewing.Extension {
constructor( viewer, options ) {
super( viewer, options );
}
load() {
this.viewer.setContextMenu( new MyContextMenu( this.viewer ) );
return true;
}
unload() {
this.viewer.setContextMenu( new Autodesk.Viewing.Extensions.ViewerObjectContextMenu( this.viewer ) );
return true;
}
}
Hope this help.

Resources