Cast recieved data from service to the correct model - angularjs

hi i have the following models:
export class Vehicle {
}
export class Trike extends Vehicle {
}
export class Car extends Vehicle {
}
These are retrieve from a Mock of an API
var vehiclesResource = vehicleService.getResource();
vehiclesResource.query((data) => {
this.areas = data;
var c = data[0] instanceof Car;
var t = data[0] instanceof Trike;
var cc = data[0].constructor === Car;
var tt = data[0].constructor === Trike;
});
A car is retrieved from the API, now when the data arrives i want to cast it to the correct object (Car in this case). but some how c = false t = false cc = false and tt = false.
setting the breakpoint in visualstudio shows me the data is of the type Object (Resource)
what am i doing wrong?

Most likely is that you are receiving data by means of deserializing it. In this case the type of the object will be lost even though its structure will be the same. For example if you do the following:
let a = new Car();
let data = JSON.stringify();
let aa = JSON.parse(data);
The type of the 'aa' object will be 'Object' and not 'Car'.
If it is acceptable you can convert you class definitions to interface definitions instead and use it like this:
let aa = <Car>JSON.parse(data);
Or you can implement your own deserialization method, more info here: How do I initialize a typescript object with a JSON object

Related

I am trying to take data from "blog" and push it to "blogs", yet an error occurs

I'm getting the following error:
**Error1:** Cannot find a differ supporting object '[object Object]' of type 'object'. NgFor only supports binding to Iterables, such as Arrays. Did you mean to use the keyvalue pipe?
**Error2:** this.blogs.push is not a function
My code looks like this:
export class BlogComponent {
blogs: Array<blogType>;
constructor() {
this.blogs = new Array<blogType>();
}
ngOnInit() {
this.blogs = JSON.parse(localStorage.getItem("blogs")!);
}
addBlog(title: any, content: any) {
let blog = new blogType(title.value, content.value);
if (localStorage.getItem('blogs')) {
this.blogs = JSON.parse(localStorage.getItem('blogs')!);
}
this.blogs.push(blog); //error occurs because of that line. Runtime error
localStorage.setItem('blogs', JSON.stringify(this.blogs));
title.value = '';
content.value = '';
alert('Blog Added!');
}
I am trying to take data from the "blog" array and push it to the "blogs" array in order to store it in the localstorage. Yet I get an error because of the folowing line: this.blogs.push(blog);
Check the contents of LocalStorage for null before you parse it and assign to this.blogs:
ngOnInit() {
var current = localStorage.getItem('blogs');
if (current !== null) {
this.blogs = JSON.parse(current);
}
console.log('this.blogs is: ' + this.blogs);
}

MobX Observable map that stores observables maps

Is this the correct way to store multiple observable maps within a store.
I'm relatively new to working with observables and MobX. I have a store for any maintenance domain object. For example "Institution Types". Instead of using a map for each I initiate a new map based off of an enum created:
maintenanceRegistry = new Map<string, any>();
selectedMaintenanceList = new Map<string, any>();
constructor() {
makeAutoObservable(this);
Object.values(MaintenanceTypeEnum).forEach((value) => {
this.maintenanceRegistry.set(value, new Map<string, any>());
});
}
And then on my onClick I set the selectedMaintenance map using the enum as the key:
if (maintenanceRegistry.get(MaintenanceTypeEnum.InstitutionTypes).size <= 1) {
loadMaintenance<InstitutionType>({apiPath: '/institutionTypes'});
} else {
setSelectedMaintenanceList(MaintenanceTypeEnum.StructureCategories);
}
When I load the data it updates my table and values however when the data has already been fetched the table data is not being updated.
To fetch the data I am using a computed function:
get maintenanceValues() {
var mv: any[] = [];
[...this.selectedMaintenanceList.values()].map((value: {value: any}, i) => {
mv.push(value);
})
return mv;
}
and then I map the data without the id property as its a guid and unnecessary:
const data = (maintenanceValues).map(value => {
const { id, ...noId } = value;
return noId
})

Type 'Observable<any>' is not assignable to type 'StoresSummaryResults'. Property 'Data' is missing in type 'Observable<any>'

I am new to using the Observable with Angular 2 and my structure will not receive the results, even though I can validate the response from my REST API.
I have the following data class in Typescript.
import { RESTResult } from '../common/RESTResult'; // Common Response Structure
import { StoresSummaryData } from './StoresSummaryData'; // Structure of records being returned as an array
export class StoresSummaryResults extends RESTResult {
Data: Array<StoresSummaryData>; // Data[] is array ofStoresSummaryData structure ({ field1, field2 ...)
constructor() {
super();
this.Data = new Array<StoresSummaryData>(); // Ensure 1 records exists for testing
this.Data.push(new StoresSummaryData(0, 0));
}
}
The results are retrieved from the REST API
getResults(): Observable<StoresSummaryResults> { // Structure
return this.http.get(this.RequestHttpPath)
.map(this.extractData)
.catch(this.handleError);
};
private extractData(res: Response) {
let body = res.json();
return body.data || {};
}
StoreInfo: StoresSummaryResults;
public constructor(private storesService: StoresService) { }
showResults(): void {
this.StoreInfo = this.storesService.getResults();
}
I get the error:
Typescript Error
Type 'Observable<StoresSummaryResults>' is not assignable to type 'StoresSummaryResults'. Property 'Data' is missing in type 'Observable<StoresSummaryResults>'.
I do have the Data structure though defined, so I am not sure what to correct.
The StoreInfo property is typed as a StoresSummaryResults, but you are trying to assign it the return value of storesService.getResults() which is Observable<StoresSummaryResults>.
So either change StoreInfo to be typed as Observable<StoresSummaryResults>, or assign it in a subscription:
this.storeSevice.getResults()
.subscribe(results => this.StoreInfo = results);

A method in controller to return two json objects

Public JsonResult GetDetails()
{
List<Cust> Customers = new List<Cust>();
Customers = GetCustomerDetails();
var name = Customers.Select(e => new{e.custname}).Distinct().ToList();
var dept = Customers.Select(e => new{e.deptname}).Distinct().ToList();
var response = new{CustomerNames = name, CustomerDepartments = dept};
return Json(response, JsonRequestBehaviour.AllowGet();
}
I have this above method returning a json object, now this method has to return a subset of this response along with the one its returning, is it possible to do a filter on department type and return two jon objects from same method.
Sure. You can add one more property to your anonymous object and return that.
public JsonResult GetDetails()
{
var customers = GetCustomerDetails();
var names = customers.Select(e => new {e.custname}).Distinct().ToList();
var depts = customers.Select(e => new { e.deptname}).Distinct().ToList();
var deptSubSet = depts.Where(f=>f.deptname=="IT").ToList();
//replace this with your condition
var response = new { CustomerNames = names,
CustomerDepartments = depts,
FilteredDepartments = deptSubSet
};
return Json(response, JsonRequestBehaviour.AllowGet();
}
Replace the Where condition linq code with whatever where clause you need to use to get the sub set.
BTW, The result is not going to be an array, It will be an object with 3 properties. The value of those properties will be an array.

How to define Java's Object[] someObject=new Object[10] in Actionscript

I have a class named Component and it has a code like this
class Component {
var ID:String;
var typical:String;
var connection:String;
var temperature:String;
var voltage:String;
var visibility:Boolean = true;
public function Component(type:String, temperature:String, connection:String, voltage:String) {
this.typical = type;
this.temperature = temperature;
this.connection = connection;
this.voltage = voltage;
}
public function setVisibility(b:Boolean):Void {
visibility = b;
}
}
I would like to create an array instance of this class just like in java (like Component[] someComponent = new Component[10]) How can I define this is Actionscript?
In Flash Player 10, Adobe added the Vector class. It is the typed array you are looking for. You can make a vector like this:
private var vector:Vector.<SomeComponent> = new Vector.<SomeComponent>(10);
private var anotherOne:Vector.<Number> = new Vector.<Number>;
thanks for the answer. I found something that might be another example.
just define an array like
var myArray:Array=new Array();
after that define each element of the array as another object, like
myArray[0]=new Component(); //Here Component is the class which I defined and showed in my original question.

Resources