Display specific data in a table - html

I have an angular project where I have a table I am populating from an api.
In the table there is a column status with three values: 1- Open, 2- Released, 3- Rejected.
displayed with,
<td>{{working_period.status}}</td>
Here's pic of the table
Image
What I want is a pipe to display only one status. E.g Only 1- open
How can I go about creating such a pipe, and is it the best solution?
I am newbie in ng7. In case of clarification let me know...please forgive my grammar.
Edit
my dashboard.component.html
<table class="table">
<thead><th>Mitarbeiter</th><th>Einsatz</th><th>Eingangsdatum</th><th>Zeitraum</th><th>Status</th></thead>
<tr *ngFor="let working_period of customers"> ...... <td>{{working_period.status}}</td></tr>
</table>
My dashboard.component.ts
import {Component, AfterViewInit, OnInit, OnDestroy, ViewChild} from '#angular/core';
import { NgbProgressbarConfig } from '#ng-bootstrap/ng-bootstrap';
import {pipe, of, Subscription} from 'rxjs';
import { first } from 'rxjs/operators';
import { ActivityReportsService } from '../../services/activity-reports.service';
import { CustomerLoginService } from '../../services/customer-login.service';
import {Customer, CustomerResponce} from '../../_models/customer';
#Component({
templateUrl: './dashboard1.component.html',
styleUrls: ['./dashboard1.component.css']
})
export class Dashboard1Component implements OnInit, OnDestroy {
currentUser: Customer;
currentUserSubscription: Subscription;
customers: Customer[] = [];
constructor(
private customerloginservice: CustomerLoginService,
private activityreportservice: ActivityReportsService
) {
this.currentUserSubscription = this.customerloginservice.currentUser.subscribe(customer => {
this.currentUser = customer;
});
}
ngOnInit() {
this.loadAllReports();
}
ngOnDestroy() {
this.currentUserSubscription.unsubscribe();
}
private loadAllReports() {
this.activityreportservice.getAll().subscribe((customers: CustomerResponce) => {
console.log(customers);
this.customers = customers.working_periods;
});
}
}

Try this (SearchPipe.pipe.ts)
import { Pipe, PipeTransform } from '#angular/core';
#Pipe({
name: 'searchFilter'
})
// Pipe to implement a search filter basd on input
export class SearchPipe implements PipeTransform {
transform(items: any[], searchTerm: string): any[] {
if (!items) { return []; }
return items.filter((val) => {
return val.status === searchTerm;
});
}
}
in HTML:
<table class="table">
<thead>
<th>Mitarbeiter</th>
<th>Einsatz</th>
<th>Eingangsdatum</th>
<th>Zeitraum</th>
<th>Status</th>
</thead>
<tr *ngFor="let working_period of customers | searchFilter:'open'"> ......
<td>{{working_period.status}}</td>
</tr>
</table>

Please create 1 function like FilterStatusData(filterstatus) which called after api get response.
In FilterStatusData modify data using loop.

You can fix it without using a pipe (Dashboard1Component)
this.customers = customers.working_periods.filter(res=>res.status==='open');

Related

Angular 'Cannot find a differ supporting object '[object Object]' of type 'object'. NgFor only supports binding to Iterables such as Arrays.'

I'm creating an Angular app which shows list of projects and list of users from postgresql database, but I'm having issues with showing list of users in html.
The problem is that Angular is considering my array as an object no matter what I do.
The same code worked for projects but didn't work for users.
This is my service:
import { environment } from "../../../environments/environment";
import { Observable } from 'rxjs';
import { Projet } from '../modele/projet.model';
import { Test } from '../modele/test.model';
import { HttpParams,HttpClient } from "#angular/common/http";
import { Injectable } from "#angular/core";
import { map } from 'rxjs/operators';
import { User } from '../modele/user.model';
import { Financement } from '../modele/financement.model';
#Injectable()
export class WebService {
constructor(private httpClient: HttpClient) { }
serverUrl: string = "http://localhost:8080/"
get(url: string): Observable<any> {
return this.httpClient.get(this.serverUrl + url);
}
}
The component :
import { Component, OnInit } from '#angular/core';
import { User } from '../../shared/modele/user.model';
import { Router } from '#angular/router';
import { WebService } from '../../shared/sevices/web.service';
import { FormGroup, FormBuilder, FormControl, Validators, Form } from '#angular/forms';
#Component({
selector: 'app-show-users',
templateUrl: './show-users.component.html',
styleUrls: ['./show-users.component.scss']
})
export class ShowUsersComponent implements OnInit {
ngOnInit(): void {
this.getData();
}
usersList: Array<User>
user: User
myForm: FormGroup;
constructor(private webService: WebService, private formBuilder: FormBuilder,private router: Router) { }
getData(): void {
this.webService.get("showUsers").subscribe(res => {
let response = JSON.parse(JSON.stringify(res))
this.usersList = response.data
})
}
}
The html :
<tr *ngFor="let user of usersList">
<td>{{user.name}}</td>
<td>{{user.username}}</td>
<td>{{user.email}}</td>
</tr>
This is the server response :
server response
NB: the EXACT same code worked for the object PROJECT
You need to make sure that the variable you pass into *ngFor is an array. You can make sure of this with Array.from(v) and can also strip any keys of an Object that might be sent from the serverside with Object.values(v):
this.webService.get("showUsers").subscribe(res => {
this.usersList = Array.from(Object.values(res.data.body.data));
})
In my case, I have a simple approach, but I spent a lot of time. You could try this:
datas: any;
this.token = JSON.parse(window.localStorage.getItem('token'));
this.authService.getData(this.token.id).subscribe(data => {
this.datas = data;
})
In the HTML template just use this.datas.id, this.datas.username instead of an *ngFor
You don't need this code:
let response = JSON.parse(JSON.stringify(res))
this.usersList = response.data
simply use:
this.userlist = res
Youe complete method:
this.webService.get("showUsers").subscribe(res => {
this.userlist = res
});

How to get values for the particular Id in Angular Using API (CRUD In Angular Using API)

I am performing CRUD In Angular using API in Laravel. I have added the values and fetched the values but I am not able to update the values using Id.
This is my app.component.ts:
import {Component } from '#angular/core';
import {HttpClient, HttpHeaders } from '#angular/common/http';
import {Employee} from './employees';
import {EditComponent} from './edit/edit.component';
import {AppService} from './app.service';
import {Router} from '#angular/router';
#Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css'],
providers: [AppService]
})
export class AppComponent {
form:any = {}
msg: string = null;
employees: Employee[];
constructor( public http: HttpClient,private appService:AppService,private router: Router)
{}
onSubmit(){
const httpOptions = {
headers: new HttpHeaders({ 'Content-Type': 'application/json' })
};
this.http.post('http://127.0.0.1:8000/api/employee',this.form,httpOptions)
.subscribe(function(s){console.log('sss',s);},function(e){console.log('e',e);});
}
ngOnInit() {
}
getEmployee():void{
this.appService.getEmployees().subscribe(employees=>(this.employees = employees))
}
}
public editComponent: boolean = false;
loadMyChildComponent($id) {
this.editComponent = true;
this.appService.setCurrentId($id);
}
}
In the loadMyChildComponent($id), I am getting the id of the row to edit.
This is my app.service.ts:
import {Injectable } from '#angular/core';
import {HttpClient,HttpParams} from '#angular/common/http';
import {HttpHeaders} from '#angular/common/http';
import {Observable} from 'rxjs';
import {Employee} from './employees';
import {EditComponent } from './edit/edit.component';
const httpOptions = {
headers: new HttpHeaders({ 'Content-Type': 'application/json' })
};
#Injectable({
providedIn: 'root'
})
export class AppService {
employee: Employee[];
id: number;
private url = 'http://localhost:8000/api/employee/';
constructor(private http: HttpClient) { }
setCurrentId(id){
this.id=id;
}
getCurrentId(){
return this.id;
}
getEmployees(): Observable<Employee[]>{
return this.http.get<Employee[]>(`http://localhost:8000/api/employees`);
}
editEmployees(id): Observable<{}>
{
const url2 = `http://localhost:8000/api/employee/${id}`;
return this.http.get<Employee[]>(url2);
}
updateEmployees(employee: Employee): Observable<any> {
return this.http.put(this.url, employee, httpOptions);
}
}
In this app.service.ts, I am getting the values for the particular ID using editEmployees(id) function.
This is my edit.component.ts:
import {Component, OnInit, Input } from '#angular/core';
import {AppService } from '../app.service';
import {Employee } from '../employees';
import {Router } from '#angular/router';
import {HttpClient, HttpHeaders } from '#angular/common/http';
import {NgForm} from '#angular/forms';
import {Observable} from 'rxjs';
import {ActivatedRoute} from '#angular/router';
import {FormBuilder, FormGroup, Validators} from "#angular/forms";
#Component({
selector: 'app-edit',
templateUrl: './edit.component.html',
styleUrls: ['./edit.component.css']
})
export class EditComponent implements OnInit {
#Input() employee: Employee;
form:any = {}
constructor(public http: HttpClient,private appService:AppService,private router: Router,private route: ActivatedRoute) { }
ngOnInit():void {
this.editEmployees();
}
editEmployees(): void {
const id = this.appService.getCurrentId();
this.appService.editEmployees(id).subscribe(employee => employee);
console.log(id);
console.log(employee);
}
onformSubmit():void{
this.appService.updateEmployees(this.form.id)
.subscribe(employee => employee = employee);
}
}
When I am printing the values in console using editEmployees() function, it is showing undefined.
This is my employees.ts:
export interface Employee{
id: number;
username:string;
email:string;
mobile:string;
password:string;
}
This is my app.component.html:
<table class="table">
<tr>
<th>Id</th>
<th>User Name</th>
<th>Email</th>
<th>Mobile</th>
<th>Edit</th>
<th>Delete</th>
</tr>
<tr *ngFor="let employee of employees">
<td>{{employee.id}}</td>
<td>{{employee.username}}</td>
<td>{{employee.email}}</td>
<td>{{employee.mobile}}</td>
<td><button (click)="loadMyChildComponent(employee.id);" class="btn btn-primary" [routerLink]="['/edit',employee.id]">Edit</button></td>
<td><button class="btn btn-danger" (click)="delete(employee)" > Delete</button></td>
</table>
The flow is that: when i click the edit button in app.component.html, It will take the id and go to app.component.ts. From app.component.ts, it will go to app.service.ts where it will fetch the values from the API using particular Id. From the app.service.ts, it will pass the values to the edit.component.ts and using edit.component.ts, it will pass the values to edit.component.html.
But the problem is that, In edit.component.ts, it is showing undefined in the editEmployees() function. Any help is much appreciated.
Change the following :
this.appService.editEmployees(id).subscribe(employee => employee);
console.log(id);
console.log(employee);
to
this.appService.editEmployees(id).subscribe(employees => {
this.employee = employees[0];
console.log(id);
console.log(employee);
});
in your edit.component file

Firebase Cloud Firestore can not load data

When I open web data is show but I change component and come back this component data not show.It show no item. I check log but not run to ngOnIt. ngOnIt run on web strat or web reload.
this is stock.service.ts
import { Injectable } from '#angular/core';
import { AngularFirestore, AngularFirestoreCollection, AngularFirestoreDocument } from 'angularfire2/firestore';
import { Observable } from 'rxjs/Observable';
import { Stock } from './stock.model';
#Injectable()
export class StockService {
stocksCollection: AngularFirestoreCollection<Stock>;
stocks: Observable<Stock[]>;
constructor(public afs: AngularFirestore) {
this.stocks = this.afs.collection('stocks').valueChanges();
}
getStock(){
return this.stocks;
}
}
stock.component.ts
import { Component, OnInit, Input } from '#angular/core';
import { ActivatedRoute,Params } from '#angular/router';
import { StockService } from '../shared/stock.service';
import { Stock } from '../shared/stock.model';
import { Brands } from '../shared/brand';
import { Subscription } from 'rxjs/Subscription';
#Component({
selector: 'app-stock',
templateUrl: './stock.component.html',
styleUrls: ['./stock.component.css']
})
export class StockComponent implements OnInit {
stocks: Stock[];
brand: Brands;
sub: Subscription;
brand_name: string;
constructor(
private stockService: StockService,
private router: ActivatedRoute
) { }
ngOnInit() {
this.stockService.getStock().subscribe(stocks => {
console.log(stocks);
this.stocks = stocks;
});
this.sub = this.router.params.subscribe(params =>{
this.brand_name = params['brand'];
});
console.log('Brand : '+this.brand_name);
}
}
and stock.component.html
<div *ngIf="stocks != null || stocks?.length > 0 ; else noStocks" >
<ul *ngFor="let item of stocks" class="collection">
<li class="collection-item " >{{item.name}} | {{item.brand}} | {{item.price}}</li>
</ul>
</div>
<ng-template #noStocks>
<p>no item</p>
</ng-template>
I don't know where code is mistake. Thank you for answer.
Don't load inside the constructor of your service, move it inside your method
constructor(public afs: AngularFirestore) {
}
getStock(){
this.stocks = this.afs.collection('stocks').valueChanges();
return this.stocks;
}

How to capture and display data from Observable?

I have a component named 'customer.component.ts'.
In this component's view there is a button called 'Search'.
What I I am doing is calling a web api method on this 'Search' button click which brings the data from sql db.
For this, I have a customer.service.ts file in which I wrote the below code -
import { Injectable } from '#angular/core';
import { Http, Response, Headers, RequestOptions } from '#angular/http';
import { Observable } from 'rxjs';
import "rxjs/add/operator/map";
import 'rxjs/add/operator/toPromise';
import { Customer, CustomerContact, CustomerHeaderAndContactsResponse, CustomerSearchRequestObjectClass, CustomerHeaderAndContactsResponse_Read } from '../models/customer';
#Injectable()
export class CustomerService {
constructor(private _http: Http) {
}
baseUrl: string = 'http://localhost/SampleApi/api/Customer/';
searchCustomers(custReqObj: CustomerSearchRequestObjectClass): observable<CustomerHeaderAndContactsResponse_Read> {
let headers = new Headers();
headers.append('Content-Type', 'application/json; charset=utf-8');
return this._http.post((this.baseUrl + 'search-customer'), JSON.stringify(custReqObj), { headers: headers }).map(res => res.json());
}
}
my customer.component.ts has the search click function -
import { Component, OnInit } from '#angular/core';
import { strictEqual } from 'assert';
import { ChangeDetectorRef } from '#angular/core';
import { stringify } from '#angular/core/src/facade/lang';
import { Customer, CustomerContact, CustomerHeaderAndContactsResponse_Read } from '../models/customer';
import { Observable } from 'rxjs/Observable';
import { CustomerService } from '../services/customer.service';
import { ChangeDetectionStrategy } from '#angular/core/src/change_detection/constants';
import { forEach } from '#angular/router/src/utils/collection';
import { AsyncPipe } from '#angular/common';
import { error } from 'util';
import { parse } from 'path';
import { Subscriber } from 'rxjs/Subscriber';
declare var $: any;
#Component({
selector: 'customer',
templateUrl: 'app/customer/views/customer.component.html',
})
export class CustomerComponent implements OnInit {
constructor(private changeDetectorRef: ChangeDetectorRef, private _custSvc: CustomerService) {
}
ngOnInit() {}
customerSearch: CustomerHeaderAndContactsResponse_Read = new CustomerHeaderAndContactsResponse_Read();
onCustomerSearchClick(): void {
this._custSvc.searchCustomers(this.custSearchReqObj).subscribe(
data => {
this.customerSearch = data;
},
err => console.log(err, 'error has occurred'),
() => console.log(this.customerSearch)
);
console.log(this.customerSearch);
}
And below is my model class -
export class CustomerHeaderAndContactsResponse_Read
{
custHeader:Customer[];
custContact:CustomerContact[];
}
Both Customer and CustomerContact classes contain some properties.
And finally here is my template where I am trying to iterate through the object the table rows simply don't display any data. I have used async (AsyncPipe) also but not helping much.
<tr *ngFor="let custItem of customerSearch.custHeader | async; let rowIndex = index">
<td>
<a (click)="onCustomerItemDetailsClick(custItem.acCustomerName, rowIndex)" class="btn">{{custItem.acCustomerName}}</a>
</td>
<td>{{custItem.acCountryId}}</td>
<td>{{custItem.acAreaId}}</td>
<td>{{custItem.acTel}}</td>
<td>{{custItem.acFax}}</td>
<td>{{custItem.acSalesContact}}</td>
<td>
<a (click)="onCustomerContactItemDeleteClick(rowIndex, 'manage-customer')" class="btn" id="btnIconDelete">
<span class="glyphicon glyphicon-trash"></span>
</a>
</td>
</tr>
Please help as I am not unable to understand what/where I am doing mistake.
Do let me know if more information is required.
Thanks in advance!
nitinthombre1991#gmail.com
EDIT -
Tried with BehaviorSubject approach, but now getting an erro like below -
Observable error
The async pipe is used to bind observables directly to the template. So here's what you can do:
data$: Observable<CustomerHeaderAndContactsResponse_Read>;
search$ = new BehaviourSubject<boolean>(true);
ngOnInit() {
this.data$ = this.search$.switchMap(searchObj => this._custSvc.search...(...));
}
onCustomerSearchClick() {
this.search$.next(true);
}
And the template looks like this
<tr *ngFor="let item of data$ | async>...</tr>
So now every time your search is clicked, it will send a call to the service and the async pipe is taking care of displaying the data in the template

Parent / Child component communication angular 2

I am failing to implement action button in child_1 component but the event handler is in sub child component child_2 as shown in the following code:
app.component.html (Parent Html)
<div style="text-align:center">
<h1>
Welcome to {{title}}!
</h1>
<app-navigation></app-navigation> <!-- Child1-->
</div>
app.component.html (Parent Component)
import { Component } from '#angular/core';
import { ProductService } from './productservice';
import {Product} from './product';
#Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css'],
})
export class AppComponent {
title = 'MobileShirtShoeApp';
}
app.module.ts (Main Module)
import { BrowserModule } from '#angular/platform-browser';
import { NgModule } from '#angular/core';
import { HttpModule } from '#angular/http';
import { Product } from './product';
import { ProductService } from './productservice';
import { AppComponent } from './app.component';
import { NavigationComponent } from './navigation/navigation.component';
import { DataTemplateComponent } from './data-template/data-template.component';
#NgModule({
declarations: [AppComponent,NavigationComponent,DataTemplateComponent],
imports: [BrowserModule,HttpModule],
providers: [ProductService],
bootstrap: [AppComponent]
})
export class AppModule { }
navigation.component.html (Child 1 HTML)
<fieldset>
<legend>Navigate</legend>
<div>
<button (click)="loadMobiles()">Mobiles</button> <!--Child_1 Action-->
</div>
<app-data-template></app-data-template>
</fieldset>
navigation.component.ts (Child 1 Component.ts)
import { Component, OnInit } from '#angular/core';
import { ProductService } from '../productservice';
import {Product} from '../product';
import {DataTemplateComponent} from '../data-template/data-template.component';
#Component({
selector: 'app-navigation',
templateUrl: './navigation.component.html',
styleUrls: ['./navigation.component.css']
})
export class NavigationComponent implements OnInit {
error: string;
productArray: Product[];
constructor(private myService: ProductService){
this.myService = myService;
}
dataTemplateComponent: DataTemplateComponent = new DataTemplateComponent(this.myService);
ngOnInit() {
}
loadMobiles() {
return this.dataTemplateComponent.loadMobiles();
}
}
data-template.component.html (Child 2 HTML) (NOT DISPLAYING DATA)
<fieldset>
<legend>Requested Data</legend>
Welcome
<div>
<ul>
<li *ngFor="let product of productArray">
{{product.id}} {{product.name}} {{product.price}}
<img src="{{product.url}}">
</li>
</ul>
</div>
</fieldset>
data-template.component.ts (Child 2 Component) (Contains Product service calling code)
import { Component} from '#angular/core';
import {Product} from '../product';
import {ProductService} from '../productservice';
#Component({
selector: 'app-data-template',
templateUrl: './data-template.component.html',
styleUrls: ['./data-template.component.css']
})
export class DataTemplateComponent {
error: string;
productArray: Product[];
constructor(private productService: ProductService) {
this.productService = productService;
}
loadMobiles(){
let promise = this.productService.fetchMobiles();
promise.then(productArr => {
return this.productArray = productArr;
}).catch((err) => {
this.error = err;
});
}
}
ProductService.ts
import 'rxjs/add/operator/toPromise';
import {Http, HttpModule} from '#angular/http';
import {Injectable} from '#angular/core';
import {Product} from './product';
#Injectable()
export class ProductService{
http: Http;
constructor(http: Http){
this.http = http;
console.log(http);
}
fetchMobiles(): Promise<Product[]>{
let url = "https://raw.githubusercontent.com/xxxxx/Other/master/JsonData/MobileData.json";
return this.http.get(url).toPromise().then((response) => {
return response.json().mobiles as Product[];
}).catch(this.handleError);
}
private handleError(error: any): Promise<any> {
console.error('An error occurred', error);
return Promise.reject(error.message || error);
}
}
Sorry if the code bothers you. So basically i am failing to display service data in child_2.html when an action made in child_1.html.The service working fine and name is ProductService which uses Product.ts as an object to get the data in JSON format. Any kind of help is appreciated.
This doesn't work because the DataTemplateComponent you're instantiating in app-navigation isn't the same instance of DataTemplateComponent as the one on the page. It's a brand new one that you instantiated and that isn't bound to the page at all. What you're trying to achieve is component communication. Specifically, parent / child component communication. There are a number of ways to do this, the cleanest and most flexible / extensible way is with a shared service pattern. Basically, you declare a service with an observable in it that you inject into both services and one updates the observable while the other is subscribed to it, like this:
#Inject()
export class MyComponentCommunicationService {
private commSubject: Subject<any> = new Subject();
comm$: Observable<any> = this.commSubject.asObservable();
notify() {
this.commSubject.next();
}
}
Then provide this service, either at the app module or possibly at the parent component depending on needs then in app navigation:
constructor(private commService: MyComponentCommunicationService) {}
loadMobiles() {
this.commservice.notify();
}
and in data template:
constructor(private commService: MyComponentCommunicationService, private productService: ProductService) {}
ngOnInit() {
this.commSub = this.commService.comm$.subscribe(e => this.loadMobiles());
}
ngOnDestroy() { this.commSub.unsubscribe(); } // always clean subscriptions
This is probably a little unneccessary since you already have the product service there. You could probably just move the load mobiles logic into the product service and have that trigger an observable that the data template service is subscribed to, and have the nav component call the load mobile method on the product service, but this is just meant to illustrate the concept.
I'd probably do it like this:
#Inject()
export class ProductService {
private productSubject: Subject<Product[]> = new Subject<Product[]>();
products$: Observable<Product[]> = this.productSubject.asObservable();
loadMobiles() {
this.fetchMobiles().then(productArr => {
this.productSubject.next(productArr);
}).catch((err) => {
this.productSubject.error(err);
});
}
}
then nav component:
loadMobiles() {
this.myService.loadMobiles();
}
then data template:
ngOnInit() {
this.productSub = this.productService.products$.subscribe(
products => this.productArray = products,
err => this.error = err
);
}
ngOnDestroy() { this.productSub.unsubscribe(); } // always clean subscriptions