I want to display only search result from firebase using angular version 8. I have data of customers stored in firebase and I want to search specific result by name.
import { Component, OnInit } from '#angular/core';
import { CustomerService } from '../shared/customer.service';
import { AngularFireDatabase } from 'angularfire2/database';
#Component({
selector: 'app-customer-list',
templateUrl: './customer-list.component.html',
styleUrls: ['./customer-list.component.css']
})
export class CustomerListComponent implements OnInit {
customerArray = [];
searchText: string = "";
findName: string;
constructor(private customerService: CustomerService) { }
ngOnInit() {
this.customerService.getCustomers().subscribe(
list => {
this.customerArray = list.map(item => {
return {
$key: item.key,
...item.payload.val()
};
});
});
}
filterCondition(customer) {
return
customer.fullName.toLowerCase().indexOf(this.searchText.toLowerCase()) != -1;
}
find(findName){
// query to check the enter name exist is firebase and display it
}
}
I expect only search data to be display but complete list of customers is displaying
You aren't ever actually using the filterCondition you have written, so of course all the customers are going to be displayed.
Its hard to tell if there aren't other problems, as you haven't specified an expected output or sample data in your question, but you at least need to change the callback you use when you subscribe to something more like this:
this.customerService.getCustomers().subscribe(
list => {
this.customerArray = list.filter(this.filterCondition).map(item => {
// contents omitted for berevity
});
});
Related
I need some help with this product getting deleted, can`t quite figure this out.
I know what has to be done on the back-end, I need some help with Angular to make this button work only with the product it has been clicked on
Thanks
This is how I intend to delete it on the back end service :
async function deleteProduct(_id){
return Product.findByIdAndDelete(_id)
}
Nothing on the controller yet :
productController.get(`/profile/delete`, async(req,res) => {
})
This is angular component :
import { Component, OnInit } from '#angular/core';
import { IProduct } from 'src/app/interfaces/products';
import { IUser } from 'src/app/interfaces/user';
import { ProfileService } from './profile.service';
#Component({
selector: 'app-profile',
templateUrl: './profile.component.html',
styleUrls: ['./profile.component.css']
})
export class ProfileComponent implements OnInit {
user: IUser|undefined
products: IProduct[] | any
isEmpty : boolean = false
constructor(private profileService: ProfileService){
}
ngOnInit(): void {
this.user = undefined
this.products = undefined
this.profileService.getUserDetails().subscribe({
next: (user) => {
this.user = user
this.products = user.products
if(this.products.length == 0){
this.isEmpty = true
}
}
})
}
deleteProduct(){}
}
As you can see most of it is empty, because I dont have any ideas. I dont want to load the page in detailed view or anything. I`d like to have this button working on this page
I assume you have in the template an ngFor (because on the image you have multiple products) and I assume product is an item of the products array. If so, well, you are almost there. You have just to pass the id parameter to the deleteProduct method like this:
deleteProduct(id: number)
{
// call the delete method
}
And don't forget to remove this product from the products array (or reload the array from the backend).
I'm fetching data from RandomUser api with Angular HttpClient. I've created a method in a service calling GET, mapping and returning a Observable. Then I subscribe on this method in a component importing this service and in subscribe's callback I am trying to store the response data in a local variable. The problem is I can't get "deeper" into this response object than:
this.randomUser.getNew().subscribe(data => {
this.userData = data[0];
})
If I'm trying to reach any further element of that response object, and log it to console it I get "undefined". To be precise I cant reference to, for example:
this.randomUser.getNew().subscribe(data => {
this.userData = data[0].name.first;
})
If I store the "data[0]" in a variable first I can get into these unreachable properties. What is the reason of it? Please, help. Let me know what important piece of fundamental JS (or Angular) knowledge I'm not aware of. As far as I know I should be able to do what I am trying to do :)
service looks like these
import { Injectable } from '#angular/core';
import { HttpClient } from '#angular/common/http';
import { map } from 'rxjs/operators';
import { Observable } from 'rxjs';
#Injectable({
providedIn: 'root'
})
export class RandomUserService {
url: string = " https://randomuser.me/api/ "
constructor(private http: HttpClient) { }
public getNew(): Observable<any> {
return this.http.get(this.url)
.pipe(map(responseData => {
const returnDataArray = [];
for (const key in responseData) {
returnDataArray.push(responseData[key])
}
return returnDataArray;
}))
}
}
component looks like these:
import { Component, OnInit } from '#angular/core';
import { RandomUserService } from 'src/app/shared/random-user.service';
import { Observable } from 'rxjs';
#Component({
selector: 'app-single-character',
templateUrl: './single-character.component.html',
styleUrls: ['./single-character.component.scss']
})
export class SingleCharacterComponent implements OnInit {
userData: object;
fname: string;
constructor(private randomUser: RandomUserService) {
this.randomUser.getNew().subscribe(data => {
this.userData = data[0];
})
}
ngOnInit(): void {
}
}
You are not parsing the returned data correctly in getNew().
The returned data looks like this:
So you need to access the user data like:
this.randomUser.getNew().subscribe(data => {
this.userData = data[0][0]; // note 2nd [0]
})
or for first name:
this.randomUser.getNew().subscribe(data => {
this.userData = data[0][0].name.first;
})
See stackblitz here: https://stackblitz.com/edit/so-http-parse?file=src/app/app.component.ts
How can i search in angular 7 using pipe (like filter in angular 1) ? Below is the code which i tried.But that returns only if exact match is there. But i need results which contains that word.
import { Pipe, PipeTransform } from '#angular/core';
#Pipe({
name: 'search',
pure:true
})
export class SearchPipe implements PipeTransform {
transform(data: any,searchTxt:string): any {
if(!data || !searchTxt)
{
return data;
}
return data.filter(function(x) {
return x.name ==searchTxt}) ;
}`
}
i tried below code also but doesn't work
return data.filter(x=>x.name.toString().toLowerCase().indexof(searchTxt.toLowerCase()) !== -1)
This throws error: x.name.indexof is not a function
How can i do contains search using javascript\angular ?
You should be using indexOf instead of === or indexof(which I think is a typo in your code).
Plus you should not be using a pipe to filter values. Here's why Angular doesn't recommend using pipes to filter or sort values.
Angular doesn't offer such pipes because they perform poorly and prevent aggressive minification. Both filter and orderBy require parameters that reference object properties. Read more about that here.
That being said, you can basically write the logic to filter data, right inside your Component:
Here, give this a try:
import { Component } from "#angular/core";
import { HttpClient } from "#angular/common/http";
#Component({
selector: "app-root",
templateUrl: "./app.component.html",
styleUrls: ["./app.component.css"]
})
export class AppComponent {
users = [];
filteredUsers = [];
constructor(private http: HttpClient) {}
ngOnInit() {
this.http
.get("https://jsonplaceholder.typicode.com/users")
.subscribe((users: any[]) => {
this.users = users;
this.filteredUsers = [...this.users];
});
}
onSearchTextChange(searchString) {
this.filteredUsers = [
...this.users.filter(user => user.name.indexOf(searchString) > -1)
];
}
}
Here's a Working CodeSandbox Sample for your ref.
I have developed a simple angular 7 web app. firebase database connectivity,
I am trying to store the first list in an array using the subscribe method and then console.log that array.
but before that data get the array will print undefined after some time it will get data.
How can code wait for the response is done and then print that array.
import { Injectable } from '#angular/core';
import { AngularFireList, AngularFireDatabase } from 'angularfire2/database';
#Injectable({
providedIn: 'root'
})
export class DressesService {
constructor(public firebase: AngularFireDatabase) { }
getJoinDresses(){
return this.firebase.list('makavana-tailor/dresses').snapshotChanges()
}
}
import { Component, OnInit } from '#angular/core';
import { DressesService } from '../../services/dresses/dresses.service';
import { map } from 'rxjs/operators';
import { Observable } from 'rxjs';
#Component({
selector: 'app-con-dress',
templateUrl: './con-dress.component.html',
styleUrls: ['./con-dress.component.css']
})
export class ConDressComponent implements OnInit {
constructor(private dresses: DressesService) { }
dressArray = [];
ngOnInit() {
this.getAllDresses();
console.log(this.dressArray)
}
getAllDresses(){
this.dresses.getJoinDresses().subscribe(actions => {
this.dressArray = actions.map(action => {
return {
$key: action.key,
...action.payload.val()
}
})
})
}
}
Your question title is not clear. But if I understand your problem correctly, you are facing an issue in working with asynchronous calls. Either you have to print console.log(this.dressArray) inside the subscribe or return the observable data from getAllDresses and subscribe to it within onInit()
code :
ngOnInit() {
this.getAllDresses().subscribe(data => {
this.dressArray = data;
console.log(this.dressArray)
});
}
getAllDresses(){
return this.dresses.getJoinDresses().pipe(map(actions => {
return actions.map(action => {
return {
$key: action.key,
...action.payload.val()
}
})
}))
}
The problem with your current code is that you show the array before it has a chance to be populated.
You know it's populated when the subscribe function is called.
So the easiest is to modify your code by moving the console.log inside the subscribe call:
ngOnInit() {
this.getAllDresses();
}
getAllDresses(){
this.dresses.getJoinDresses().subscribe(actions => {
this.dressArray = actions.map(action => ({
$key: action.key,
...action.payload.val()
}));
console.log(this.dressArray);
})
}
I want to get all the data from github API. But it doesn't work for me.
My .ts file is below:
import { Component } from '#angular/core';
import { GitTakeService } from "app/git-take.service";
#Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
user:any;
constructor(private gittakeService:GitTakeService ){
this.gittakeService.getUser().subscribe(user=>{
debugger;
this.user=user;
console.log(user);
})
}
}
My service is below:
import { Injectable } from '#angular/core';
import {Http,Response, Headers} from '#angular/http'
import'rxjs/add/operator/map';
#Injectable()
export class GitTakeService {
constructor(private http:Http) { }
getUser(){
debugger;
return this.http.get("http://api.github.com/users")
.map(
(resp:Response)=>{
return resp.json().response;
}
);
}
}
When consoling the user in .ts file, it shows undefined. My view file is like this:
{{user}}
Anyone please help me to solve this problem?
What you are receiving is an array, so you want to use resp.json() instead of resp.json().response there is no such property like response in your response. So your map should look like this:
getUser(){
debugger;
return this.http.get("http://api.github.com/users")
.map((resp:Response)=>{
return resp.json();
});
}
and in your component I would name the array users instead of user, since there are several users in your response. Also I suggest you keep anything unnecessary from the constructor and use OnInit instead:
users = [];
constructor(private gittakeService:GitTakeService ){ }
ngOnInit() {
this.gittakeService.getUser()
.subscribe(data => {
this.users = data;
});
}
Then you can iterate the array and use the property names to show the properties of one user object:
<div *ngFor="let user of users">
{{user.login}}
</div>
resp.json().response is undefined resp.json() is what you want
the service function:
getUser(){
return this.http.get("http://api.github.com/users")
.map(
(resp:Response)=>{
return resp.json();
}
);
}`
and the component:
this.gittakeService.getUser().subscribe(users=>{
this.user=users[0];
console.log(user);
})