I have created a simple form on the Asp.net boiler template project. I have a total of three fields
In Table 1
Product name
Quantity
In Table2
Tags with product List
I wanted to store third field data in another table in the database.
but I'm confused as I'm a beginner.
The product name and quantity is working fine. Can someone please guide me? Why data in the 2nd table is stored as null?
(1) This is chips code ( from priming)
(2) This is my class code (in which all three data members exist
(3) This is my Product list class code for storing chips
(4) This is database table of Product
(5) This is Database table of Product list class
This is new attached image
Error Image
import {Component,Injector,OnInit,EventEmitter,Output,} from '#angular/core';
import { finalize } from 'rxjs/operators';
import { BsModalRef } from 'ngx-bootstrap/modal';
import * as _ from 'lodash';
import { AppComponentBase } from '#shared/app-component-base';
import {
ProductServiceProxy,
ProductDto,
Product_listDto,
Product_listServiceProxy
} from '#shared/service-proxies/service-proxies';
#Component({
templateUrl: 'create-product.component.html'
})
export class CreateProductComponent extends AppComponentBase
implements OnInit {
saving = false;
product = new ProductDto();
#Output() onSave = new EventEmitter<any>();
constructor(
injector: Injector,
private _productService: ProductServiceProxy,
public bsModalRef: BsModalRef
) {
super(injector);
}
ngOnInit(): void {
}
save(): void {
this.saving = true;
console.log("input",this.product)
const product = new ProductDto();
product.init(this.product);
this._productService
.create(product)
.pipe(
finalize(() => {
this.saving = false;
})
)
.subscribe(() => {
this.notify.info(this.l('SavedSuccessfully'));
this.bsModalRef.hide();
this.onSave.emit();
});
}
}
Your p-chip returns a string array but your back end requiring a object of product_list.you need to pass the a `product_list' object array to the backend.
save(): void {
this.saving = true;
console.log("input",this.product)
let productList = [...this.product.productList];
this.product.productList = productList.map(item=>{
return {
Id: 0,
Name: item
}
});
const product = new ProductDto();
product.init(this.product);
}
Related
I went through this issue while working on the ScheduleJS framework. At some point I am provided with a HTMLCanvasElement which I want to replace with a dynamically generated component programatically. To do so, and to keep the code as clean as possible, I'd like to create my own Angular components at runtime and use the HTMLCanvasElement.replaceWith(component) method from the provided HTMLCanvasElement replacing the canvas with the dynamically created component.
Here is the Angular service I came up with, which does the job the way I expected:
import {ApplicationRef, ComponentFactoryResolver, ComponentRef, Injectable, Injector, Type} from "#angular/core";
import {ReplacementComponent} from "xxx"; // This is a higher order type of Component
#Injectable({providedIn: "root"})
export class DynamicComponentGenerator {
// Attributes
private _components: Map<string, ComponentRef<ReplacementComponent>> = new Map();
private _currentKey: number = 0;
// Constructor
constructor(private _appRef: ApplicationRef,
private _resolver: ComponentFactoryResolver,
private _injector: Injector) { }
// Methods
create(componentType: Type<ReplacementComponent>): ComponentRef<ReplacementComponent> {
const componentRef = componentType instanceof ComponentRef
? componentType
: this._resolver.resolveComponentFactory(componentType).create(this._injector);
this._appRef.attachView(componentRef.hostView);
this._components.set(`${this._currentKey}`, componentRef);
componentRef.instance.key = `${this._currentKey}`;
this._currentKey += 1;
return componentRef;
}
remove(componentKey: string): void {
const componentRef = this._components.get(componentKey);
if (componentRef) {
this._appRef.detachView(componentRef.hostView);
componentRef.destroy();
this._components.delete(componentKey);
}
}
clear(): void {
this._components.forEach((componentRef, key) => {
this._appRef.detachView(componentRef.hostView);
componentRef.destroy();
this._components.delete(key);
});
this._currentKey = 0;
}
}
So basically this service lets me create a component with .create(ComponentClass) remove it by providing the component key .remove(key) and clear() to remove all the components.
My issues are the following:
The ComponentFactoryResolver class is deprecated, should I use it anyways?
Could not manage to use the newer API to create unattached components (not able to have access to an Angular hostView)
Is there a better way to do this?
Thank you for reading me.
You could try using new createComponent function:
import { createComponent, ... } from "#angular/core";
const componentRef =
createComponent(componentType, { environmentInjector: this._appRef.injector});
this._appRef.attachView(componentRef.hostView);
i have my service with 2 methods getAll() and getById(), from which i receive the data:
job.service.ts
export class JobService {
constructor(private http: HttpClient) {}
url: string =
'https://api.json-generator.com/templates/......../data?access_token=............';
getAll(): Observable<Jobs[]> {
return this.http.get<Jobs[]>(this.url)
}
getById(id: string): Observable<Jobs> {
const path = `${this.url}`;
return this.http.get<Jobs>(path)
}
}
with getAll() method i form a list of items, from where with routerLink and *queryParams * i need to go to the separate page of item, that i clicked
job-list-card.component.html
<a routerLink="/details" [queryParams]="{ id: jobs.id }">
<h2 class="card-info__title">
{{ jobs.title }}
</h2>
</a>
and here is my the separate page of item ts-file:
job-detail.component.ts
export class JobDetailComponent implements OnInit {
jobs: Jobs | undefined;
constructor(
private route: ActivatedRoute,
private location: Location,
private jobService: JobService
) {}
ngOnInit(): void {
this.getJob();
}
getJob(): void {
const id = String(this.route.snapshot.paramMap.get('id'));
this.jobService.getById(id)
.subscribe(jobs => this.jobs = jobs);
}
goBack(): void {
this.location.back();
}
}
but everything i get in my page is only template without any api data.
so, what's wrong with my service or job-detail?
how can i get one item from list of items, that i receive from remote JSON API?
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>
I have a button on my nav bar (app.component.html) that I want to only show when the user is logged in.
This is my current approach that does not work for obvious reasons explained later. I want to find out how I can modify it to work.
Inside my app.component.html, I have the following button
<button *ngIf="isCurrentUserExist">MyButton</button>
Inside my app.component.ts, I am trying to bound the variable isCurrentUserExist to a function that returns true if the user exists.
I believe this is the problem because this code is only executed once at OnInit as oppose to somehow keeping the view updated
ngOnInit() {
this.isCurrentUserExist = this.userService.isCurrentUserExist();
}
For reference, inside my UserService.ts
export class UserService {
private currentUser: User
constructor(private http: Http,private angularFire: AngularFire) { }
getCurrentUser(): User {
return this.currentUser
}
setCurrentUser(user: User) {
this.currentUser = user;
}
isCurrentUserExist(): boolean {
if (this.currentUser) {
return true
}
return false
}
}
A bit more information about my app...
Upon start up when the user does not exist, I have a login screen (login component).
When the user logs in, it goes to firebase and grab the user information (async) and store it to my user service via
setCurrentUser(user: User)
So at this point, I like to update the button in my nav bar (which exists in app.component.html) and show the button.
What can I do to achieve this?
let's try this:
using BehaviorSubject
UserService.ts
import { Subject, BehaviorSubject} from 'rxjs';
export class UserService {
private currentUser: User;
public loggedIn: Subject = new BehaviorSubject<boolean>(false);
constructor(private http: Http,private angularFire: AngularFire) { }
getCurrentUser(): User {
return this.currentUser
}
setCurrentUser(user: User) { // this method must call when async process - grab firebase info - finished
this.currentUser = user;
this.loggedIn.next(true);
}
isCurrentUserExist(): boolean {
if (this.currentUser) {
return true
}
return false
}
}
app.component.ts
ngOnInit() {
this.userService.loggedIn.subscribe(response => this.isCurrentUserExist = response);
}
in app.component.ts you are assigned value from function once. So it will never change. To resolve this problem and to real time update use assign function instance of boolean variable this.isCurrentUserExist = this.userService.isCurrentUserExist;. And in view change change *ngIf expression as function isCurrentUserExist().
Thanks to tutorial on Angular 2 page called "Tour of Heroes", I managed to create a simple Angular 2 application. Then using Enitity Framework I decided to create a database. And fill the list of heroes from it (not from the file). I created Web Api Controller and added simple get method.
Then in hero.service.ts I call this method in order to get list of heroes. When I lunch my app it shows the list of heroes but without any values (name and id are blank). When I debug my application in the browser I can see this.heroes object in heroes.component.ts contains right data. So what is going on? Why aren't name and id showing?
hero.service.ts:
import {Injectable} from 'angular2/core';
import {HEROES} from './mock-heroes';
import {Hero} from './hero';
import {Http, Response} from 'angular2/http';
import 'rxjs/Rx';
import {Observable} from 'rxjs/Observable';
#Injectable()
export class HeroService {
public values: any;
constructor(public _http: Http) { }
private _heroesUrl = 'http://localhost:61553/api/values'; // URL to web api
getHeroes() {
return this._http.get(this._heroesUrl)
.map(res => <Hero[]>res.json())
.catch(this.handleError);
}
private handleError(error: Response) {
console.error(error);
return Observable.throw(error.json().error || 'Server error');
}
}
heroes.component.ts:
import {Component, OnInit} from 'angular2/core';
import {Router} from 'angular2/router';
import {Hero} from './hero';
import {HeroDetailComponent} from './hero-detail.component';
import {HeroService} from './hero.service';
#Component({
selector: 'my-heroes',
templateUrl: 'templates/heroes.component.html',
styleUrls: ['styles/heroes-component.css'],
directives: [HeroDetailComponent]
})
export class HeroesComponent implements OnInit {
constructor(private _heroservice: HeroService, private _router: Router) { }
errorMessage: string;
public heroes: Hero[];
selectedHero: Hero;
ngOnInit() {
this.getHeroes();
}
onSelect(hero: Hero)
{
this.selectedHero = hero;
}
getHeroes() {
this._heroservice.getHeroes()
.subscribe(
value => this.heroes = value,
error => this.errorMessage = <any>error);
}
gotoDetail() {
this._router.navigate(['HeroDetail', { id: this.selectedHero.Id }]);
}
}
heroes.component.html:
<h2>My Heroes</h2>
<ul class="heroes">
<li *ngFor="#hero of heroes" [class.selected]="hero === selectedHero" (click)="onSelect(hero)">
<span class="badge">{{hero.Id}}</span> {{hero.Name}}
</li>
</ul>
<div *ngIf="selectedHero">
<h2>
{{selectedHero.Name | uppercase}} is my hero
</h2>
<button (click)="gotoDetail()">View Details</button>
</div>
hero.ts:
export class Hero {
Id: number;
Name: string;
}
Web API Controller:
using Microsoft.AspNet.Mvc;
using System.Collections.Generic;
using TestApplicationDataAccess;
using TestApplicationDataAccess.Entities;
namespace WebApplication2.Controllers
{
[Route("api/[controller]")]
public class ValuesController : Controller
{
private readonly TestAppDbContext _dbContext;
public ValuesController(TestAppDbContext dbContext)
{
_dbContext = dbContext;
}
// GET: api/values
[HttpGet]
public IEnumerable<Hero> Get()
{
return _dbContext.Heroes;
}
}
}
Hero Entity:
namespace TestApplicationDataAccess.Entities
{
public class Hero
{
public int Id { get; set; }
public string Name { get; set; }
}
}
JSON retrieved from WEB API Controller:
[{"Id":1,"Name":"Superman"}]
getHeroes() {
this._heroservice.getHeroes()
.subscribe(res=>{
this.heroes=res;
console.log(this.heroes); // make sure you get data here.
},
(err)=>console.log(err),
()=>console.log("Done")
);
}
Try this :public heroes: Hero[] = [];
In my case the issue was related to the visual studio 2015 bug. There was nothing wrong with the code itself. Sometimes changes made in vs were not refreshed in the browser. Updating vs to the latest version helped.