Angular 2 : Modified import Model don't update in view - html

I changed my model to fit requirements for uusing entityframework but the view related to this model can't use the new model wich is :
export class CV {
public Id: number;
public UserId: string;
public Context: string;
public Competences: Array<Competence>;
public Expertises: Array<Expertise>;
public Formations: Array<Formation>;
public Missions: Array<Mission>;
}
The model before changing is :
export class CV {
public id: number;
public userId: string;
public context: string;
public competences: Array<Competence>;
public expertises: Array<Expertise>;
public formations: Array<Formation>;
public missions: Array<Mission>;
Example, I show an object from my console :
Screenshot from my chrome console
So I want to update the model in my view but I don't know how. I tried different things like ChangeDetectorRef but nothing is working.
Thank you in advance for your help !

I'd suggest you'd use Interfaces instead of classes, since at looking at the model, you don't need a class. So change it to an interface instead:
export interface CV {
Id: number;
UserId: string;
Context: string;
Competences: Array<Competence>;
Expertises: Array<Expertise>;
Formations: Array<Formation>;
Missions: Array<Mission>;
}
Since your property names do not match the data you are receiving, you need to map the values and set the data with the properties that match your model.
So your service function should look something like this:
getData() {
return this.http.get('the url')
.map(res => res.json().map((x:any) =>
Object.assign({Id:x.id,UserId:x.userId,/* Rest of the properties here */})))
}
And then in your component you subscribe normally and assign the incoming data as an array of type CV.

Related

ERROR NullInjectorError: R3InjectorError(AppModule)[Number -> Number -> Number]: NullInjectorError: No provider for Number

I'm not sure what is going on here. The application was working fine then I came in to work on it and kept getting this error. My Compiler doesn't show errors, and I do not have any nulls in the code (or at least I don't think i do.) Here is what the console looks like:
Any help would be appreciated here. I'm trying to learn TS, Angular, and RxJS so still a noob. lol
We inject dependencies using the constructor generally.
Read this: https://angular.io/guide/dependency-injection
Your code should be
//...
public Bug_Number: number,
public Bug_Name: string,
public Created_By: string,
public Detail: string,
public Date_Started: number,
public Date_Completed: number,
public Date_Days_Worked: number,
public Completed: string
constructor() { }
//...
We usually inject a service/class by marking them as injectable using the #Injectable decorator
Example: Bug Service
import { Injectable } from '#angular/core';
#Injectable({
providedIn: 'root',
})
export class BugService {
constructor() { }
// getBug()
// getBugById(bugId: number)
// addBug(Bug bug)
}
And inject it in component like,
constructor(bugService: BugService) { }
and access them anywhere in page like this.bugService.getBugs()

Dynamically loading json file by package name (Typescript)

I am trying to write a small browser game in Typescript. So to start, I have a Scenario class that would need to load characters' dialogues based on scenario names.
Here is how the Scenario class looks like:
export class Scenario extends Entity{
public characters: Character[] = [];
constructor(
public readonly scenarionName: string,
public readonly startDialogueId: string
) {
super();
}
public awake() {
this.loadCharacters();
}
private loadCharacters(){
this.characters = [];
// FIXME how can I dynamically load dialogues based on scenario name?
}
}
My idea was to have dialogues stored in JSON files, which would then be loaded based on the scenario name, which would also be a package name. Here how it looks:
In this case, I want to dynamically load 'npc.json' and 'player.json' into Scenario class based on the scenario name which in this case is a 'test'. In the future, there would be more scenarios and I would like to avoid hard coding.
Can this be done in such a way and if so, how?
EDIT: the game would run in the browser.
Use fs module to get the file names in a directory and read the contents of the files.
import fs from('fs');
export class Scenario extends Entity{
public characters: Character[] = [];
constructor(
public readonly scenarionName: string,
public readonly startDialogueId: string,
scenarioPath: string
) {
super();
}
public awake() {
this.loadCharacters();
}
private loadCharacters(){
this.characters = [];
const dialoguesDir = `${this.scenarioPath}/${this.scenarioName}/dialogues/`;
let dialogueContent;
fs.readdirSync(dialoguesDir).forEach(filePath => {
dialogueContent = fs.readFileSync(`${dialoguesDir}${filePath}`).toString();
// Do something with contents
});
}
}

objects parsing in html component in angular

I want to use an object in #input parameter in the html.
for example:
<app-home [param]="user.salary"></app-home>
but the type of my user is something like that:
user:Person=new Employee();
my classes are:
export class Person {
constructor(public name:string){}
}
export class Employee extends Person {
constructor(public name:string,
public salary:number){
super(name);
}
}
how do I parse the user in the #input parameter to Employee?
I tried to do so:
<app-home [param]="(user as Employee).salary"></app-home>
but I get an error. so how can I do it?
If you want to pass the complete object, and as I may assume you're already defining it, change the param class to handle to object
class HomeComponent{
#Input() param: Employee;
}
then pass the object instead of a simgle property
<home-component [param]="user"></home-component>
This way you're getting the full component and you can now access and manipulate all it's properties.
If you have an object in home-component that you want to define by passing the user to it, try using a setter, like this
class homeComponent{
private _user:Employee;
#Input()
set param(data) {
this._user = data;
}
}
Or you can destructure it to handle easily each property and assign individually
class homeComponent{
private _user:Employee;
#Input()
set param({name, salary}) {
this._user = new Employee(name, salary)
}
}
If your User object is missing salary and you want to assign it after passing to the HomeComponent, you can try this
class homeComponent{
private _employee:Employee;
private _salary:number = 2000;
#Input()
set param(data) {
this._employee = new Employee({...data, salary: this._salary})
}
}
This way, you're getting your entire object, and trigger the setter to complete it's definition by adding the salary property;

Angular2 - Unresolved Variables

Complete noob looking for help,
I've been learning Angular2 and attempting to make a basic app but now its broken!
The component.ts file
import {Component, OnInit} from '#angular/core';
import { Player } from './player.model';
#Component({
selector : 'app-player',
templateUrl : '/player.component.html'
})
export class PlayerComponent implements OnInit {
players: Player[] = [
new Player('Malus', 'Lina', 'lol', 3000)
];
constructor() {}
ngOnInit() {}
}
model.ts
export class Player {
public playerName: string;
public favHero: string;
public heroImage: string;
public mmr: number;
constructor( name: string, favHero: string, heroImage: string, mmr: number) {
this.playerName = name;
this.favHero = favHero;
this.heroImage = heroImage;
this.mmr = mmr;
}
}
lastly where the error is in the HTML
I am trying to use {{ players.playerName }} etc but they are unresolved? I think this is why my app is broken now
apparently, the variables of my array are unresolved?. I don't get it and cant work out why.
Appreciate any help thanks
You are trying to access an object key of an array (players.playerName), which you can't do. You either need to access a particular index players[0].playerName or loop through your players and create a DOM block for each player
<div *ngFor="let player of players">
{{player.playerName}}
</div>

Angular 2/ Type Script classes to JSON object

I am trying to create a class that can use to send a json object to a REST API. This is the json object that i need to send.
{
"libraryName": "temp",
"triggerName": "trigger",
"currentVersion": "1.3",
"createdUser": "xyz",
"visibilityType": "private",
"WFAllowdTeam": {
"allowedTeam": "team1"
},
"WFLibraryHistory": {
"createdDate": "2016-7-7T05:10:04.106Z",
"modifiedDate": "2016-7-9T05:10:04.106Z"
}
}
I tried creating a class like this and tried to set the data by creating an object this.library.WFAllowdTeam.WFAllowdTeam = 'team';, Please find the class i created here,
class WFLibraryHistory {
public createdDate: any;
public modifiedDate: any;
}
class WFAllowdTeam {
public WFAllowdTeam: string;
}
export class Library {
public libraryName: string;
public triggerName: string;
public currentVersion: string;
public createdUser: string;
public visibilityType: string;
public libraryID: string;
WFLibraryHistory: WFLibraryHistory;
WFAllowdTeam: WFAllowdTeam;
}
The error is,
platform-browser.umd.js:937 TypeError: Cannot set property 'WFAllowdTeam' of undefined
at WFLibraryComponentAddNewWorkflow.createWorkflow (wf-library.component.new.workflow.ts:47)
at DebugAppView._View_WFLibraryComponentAddNewWorkflow0._handle_click_61_0 (WFLibraryComponentAddNewWorkflow.ngfactory.js:488)
at eval (core.umd.js:12718)
at SafeSubscriber.schedulerFn [as _next] (core.umd.js:9181)
at SafeSubscriber.__tryOrUnsub (Subscriber.ts:240)
at SafeSubscriber.next (Subscriber.ts:192)
at Subscriber._next (Subscriber.ts:133)
at Subscriber.next (Subscriber.ts:93)
at EventEmitter.Subject._finalNext (Subject.ts:154)
at EventEmitter.Subject._next (Subject.ts:144)
Any help to overcome this issue will be really appreciated.
You need to instantiate those (class) members first.
export class Library {
public libraryName: string;
public triggerName: string;
public currentVersion: string;
public createdUser: string;
public visibilityType: string;
public libraryID: string;
WFLibraryHistory: WFLibraryHistory;
WFAllowdTeam: WFAllowdTeam;
constructor() {
this.WFLibraryHistory = new WFLibraryHistory();
this.WFAllowdTeam = new WFAllowdTeam();
}
}
You need to create an instance of WFAllowdTeam before you can modify any of its properties.
this.library.WFAllowdTeam = new WFAllowdTeam();
this.library.WFAllowdTeam.WFAllowdTeam = 'team';