In angular, when a page is opened in edit mode using query params, value in dropdown is not coming in mat select - ngmodel

customer_name is not displayed in dropdown.
In .ts file, in ngOnInit() I have used query params to open a page in edit mode.
ngOnInit(): void {
this.addInvoiceItem();
this.route.queryParams.subscribe((params) => {
if (params._id === undefined) {
this.isEdit = true;
console.log(this.isEdit);
} else {
this._id = params._id;
this.service.fetchInvoiceById(this._id).subscribe((data) => {
this.invoice = data;
console.log(this.invoice.customer_details);
this.customerService
.fetchCustomerById(this.invoice.customer_details)
.subscribe((data) => {
this.invoice.customer_details = data;
console.log(this.invoice.customer_details);
});
});
}
this.customerService.fetchAllCustomers().subscribe((data) => {
this.custList = data;
console.table(this.custList);
});
this.availService.fetchAllCustomers().subscribe((data) => {
this.servicesList = data;
console.table(this.servicesList);
});
});
}
In console.log(this.invoice.customer_details) I can see customer_name in debug. But in display customer_name is not coming.
In html file,
<mat-select
name="customer_details"
[(ngModel)]="invoice.customer_details"
#customer_details="ngModel"
(selectionChange)="updateAddress()"
required
[displayWith]="displayCustomer"
>
<mat-option
*ngFor="let cust of custList"
[value]="cust"
required
>
{{ cust.customer_name }}
</mat-option>
</mat-select>

Related

Edit API Dropdown

I populated the country list in my select option and when I click on country in user menu data save successfully and afterward while updating the user field the country name is not showing/or the old list from api loads this happens in laravel 08
Code to populate select option
document.addEventListener('DOMContentLoaded', () => {
const selectDrop = document.querySelector('#countries');
// const selectDrop = document.getElementById('countries');
fetch('https://restcountries.com/v3.1/all').then(res => {
return res.json();
}).then(data => {
let output = "";
data.forEach(country => {
console.log(country.name.common)
output += `<option value="${country.name.common}">${country.name.common}</option>`;
})
selectDrop.innerHTML = output;
}).catch(err => {
console.log(err);
})
});
here is my controller
public function update(Request $request){
try{
$user= User::data_update($request);
return view ('profile_edit', ['user'=>$user]);
}catch (\Exception $exception){
return $exception;
}
}
here is my model
public static function data_update($user1)
{
$user = self::user_data();
$user->name = $user1['name'];
$user->email = $user1['email'];
$user->phone = $user1['phone'];
$user->gender = $user1['gender'];
$user->country = $user1['country'];
$status = $user->save();
return $user;
}
here is my blade
<div class="col-sm-9 text-secondary">
<select id="countries" name="country">
<option value="{{$user->country}}" selected ></option>
</select>
</div>

Laravel + Vue 3: Upload files with categories

I'm working on uploading multiple files using Laravel and Vue 3. File uploading is doing fine until I added a select tag in the form for the category. I put the category and files into one object so I can pass only 1 parameter. Now in TestController I can get the value of category but giving me error in files.
I need to:
Pass category and files
Read category and files so I can move and save info to database
test.vue
<form #submit.prevent="upload" enctype="multipart/form-data">
<!-- added this tag for category -->
<select v-model="category">
<option v-for="type in categories" :key="type.id" :value="type.id">
{{ type.name }}
</option>
</select>
<input type="file" multiple #change="fileChange">
<button type="submit">Upload</button>
</form>
<script>
import useTest from "../composables/test.js"
import { onMounted } from 'vue'
export default {
setup() {
const { categories, getCategories, uploadFile } = useTest()
onMounted(getCategories)
const attachments = []
const category = 1 // added for category
const upload = async () => {
// const formData = new FormData // without category
// with category, I put inside an object so I can pass only 1 parameter
const form = {
category: category.value,
files: new FormData,
}
// loop to append
Object.keys(attachments).forEach(
// key => formData.append(key, attachments[key]) // without category
key => form.files.append(key, attachments[key]) // with category
)
// call from composable
await uploadFile(form)
}
return {
categories,
category,
upload,
}
},
}
</script>
composable: test.js
import { ref } from 'vue'
import axios from 'axios'
export default function useTest() {
const categories = ref([])
const getCategories = async () => {
let response = await axios.get("/api/fileUpload/")
categories.value = response.data.categories
}
const uploadFile = async (form) => {
// METHOD IS INSIDE TRY CATCH BLOCK
const config = {headers: { 'content-type': 'multipart/form-data' }}
// let response = await axios.post("/api/fileUpload/", form, config)
let response = await axios.post("/api/fileUpload/", form)
console.log(response);
}
return {
categories,
getCategories,
uploadFile,
}
}
TestController
public function store(Request $request)
{
// $uploadFiles = $request; // without category
$uploadFiles = $request['files']; // with category
$uploadFiles = $request['category'];
error_log($uploadFiles);
// error here: Attempt to read property \"files\" on array
foreach ($uploadFiles->file as $file) {
error_log('here');
error_log($file->getClientOriginalName());
error_log($file->getClientOriginalExtension());
error_log($file->getSize());
error_log($file->getMimeType());
error_log(date("m/d/Y H:i:s.",filemtime($file)));
error_log('---------------------');
}
return response()->json(['status'=>'success'], status: 200);
}

Search bar (ionInput) event to filter output

I am using search bar ionInput event to search among the list but filtered output is shown for one list and not shown for other list on other page?
my first list code :-
HTML
<ion-searchbar class="ion-no-padding" showcancelbutton="true" (ionInput)="onSearchChange($event)" placeholder="search manga"></ion-searchbar>
<ion-list no-lines *ngFor="let anime of animelist" >
<ion-item>
<h2>Name : {{anime.t}}</h2>
</ion-item>
</ion-list>
My .ts file
getanimelist(){
this.restProvider.getanimelist().subscribe(data => {
this.animelist = data;
console.log('result ' + JSON.stringify(data) );
});
this.items= this.animelist;
}
onSearchChange(evt: any) {
this.getanimelist();
console.log(this.items);
console.log(evt);
const val = evt.srcElement.value;
console.log(val);
if (!val){
return ;
}
this.animelist = this.items.filter((data) => {
// console.log(data);
if (data.t && val){
if (data.t.toLowerCase().indexOf(val.toLowerCase()) > -1){
return true;
}
return false;
}
})
}
my api call for this:-
apiUrl= 'https://www.mangaeden.com/api';
getanimelist(){
return this.http.get(this.apiUrl+'/list/0').pipe(
map(result => {
return result['manga'];
})
)}
}
the output for this list does get filter and my list do get updated on the page as per the value enterd but for my second list on other page iam using the same concept same code but my output is not getting filtered on the page, inside the console log i see the filtered result but my page list is not getting updated
second list code below :-
HTML
<ion-searchbar class="ion-no-padding" showcancelbutton="true" (ionInput)="onSearchChange($event)" placeholder="search manga"></ion-searchbar>
<ion-list no-lines *ngFor="let anime of animelist" >
<ion-item >
<h2>Name : {{anime.t}}</h2>
</ion-item>
</ion-list>
My .ts file
getanimelist(){
//this.isLoaded = true;
this.restProvider.getpageanimelist().subscribe(data => {
this.animelist = data;
//console.log('result ' + JSON.stringify(data) );
});
this.items= this.animelist;
}
onSearchChange(evt: any) {
this.getanimelist();
const val = evt.srcElement.value;
console.log(this.items);
console.log(evt);
console.log(val);
if (!val){
return ;
}
this.animelist = this.items.filter((data) => {
// console.log(data);
if (data.t && val){
if (data.t.toLowerCase().indexOf(val.toLowerCase()) > -1){
return true;
}
return false;
}
});
}
my api call for the 2nd list:-
getpageanimelist(){
return this.http.get(this.apiUrl+'/list/0/?p=0&l=26').pipe(
map(result => {
return result['manga'];
})
)}
hope someone can help why is the filtered result not shown for my 2nd list ?
I stored the filter data in a new array rather than in animelist array (which is getting data from the api in the subscribe block) which was causing the whole array to call again and hence no filtered data can be viewed
my changed code in .ts
onSearchChange(evt: any) {
this.getanimelist();
const val = evt.srcElement.value;
if (!val){
return ;
}
this.newarray = this.items.filter((data) => { //stored data in new array
if (data.t && val){
if (data.t.toLowerCase().indexOf(val.toLowerCase()) > -1){
return true;
}
return false;
}
})
}
and hence i call the new array in my html and now when i type the name of the anime the list get filtered accordingly without any issue.
Changed Html
<ion-searchbar class="ion-no-padding" showcancelbutton="true" (ionInput)="onSearchChange($event)" placeholder="search manga"></ion-searchbar>
<ion-list no-lines *ngFor="let anime of newarray" >
<ion-item >
<h2>Name : {{anime.t}}</h2>
</ion-item>
</ion-list>

Trying to display a values from multiple API fetch

Currently I'm reading some stock/share names from my DB (Mongo) and trying to display their price by calling an API for each one of them on my component, but I'm getting only the last one.
HTML
<div class="posts-container">
<div class="post" v-for="post in posts"
v-bind:key="post['2. Symbol'] " >
<p class="text">{{ post['2. Symbol'] }} </p>
</div>
</div>
JS
data(){
return {
posts: [],
error: '',
text: ''
}
},
async created() {
try {
const acoes = await APIService.getPosts();
acoes.map(data => {
fetch(`https://www.alphavantage.co/query?function=TIME_SERIES_INTRADAY&symbol=${data.name}.SA&interval=15min&outputsize=compact`)
.then(res => res.json())
.then(data => {
this.posts = { ...this.posts, ...data}
});
})
console.log(this.posts);
} catch (err) {
this.error = err.message;
}
},
So as I have multiple values on my const acoes I expected to generate data for each one of them, but what I got is just for the last object.
What am I missing here?
There's a smarter way of doing this instead of calling the API on the component?
You can use Promise.all to combine all your result.
const allFetches = acoes.map(
data => fetch(...)
.then(response => response.json()
)
Promise.all(allFetches)
.flatMap(result => result)
.then(posts => {
this.posts = posts;
});

How to filter the data from API json using ionic?

I would like to have a search bar that filters the results I tried to do it but it does not work. When I'm looking for something, nothing happens, no mistake, so I'm wrong, but I do not know what, I'm new to typescript and I ask for help. Thanks in advance
Home.html
---------
<ion-searchbar (ionInput)="filterItems()"
[showCancelButton]="shouldShowCancel" (ionCancel)="onCancel($event)"></ion-searchbar>
<ion-list>
<ion-item *ngFor="let item of items" (click)="itemClick(item.id)">
<h1>{{item.id}}</h1>
{{item.title}}
</ion-item>
</ion-list>
Home.ts
-------
export class HomePage {
public items:any;
constructor(public http:HttpClient) {
this.loadData();
}
searchTerm: string ;
loadData() {
let data:Observable<any>;
data = this.http.get('https://jsonplaceholder.typicode.com/photos');
data.subscribe(result => {
this.items = result;
this.filterItems= this.items;
})
}
filterItems(ev:any){
this.loadData();
const val = ev.target.value;
this.filterItems = this.items.filter(item =>
{
item.titre.toLowerCase().indexOf(this.searchTerm.toLowerCase()) > -1;
})
}
itemClick(itemid:number){
alert(itemid);
}
}
so you can do this in your html
<ion-searchbar [formControl]="searchTerm"></ion-searchbar>
Then in your .ts file declare before the constructor
public searchTerm: FormControl;
Then inside your ngOnInit, have this function that listens to user input and waits a while before filtering
this.searchTerm.valueChanges
.pipe(debounceTime(700))
.subscribe(search => {
this.items = this.filterItems(search);
});
Then your final method for the filter
filterItems(search) {
this.items = this.filterItems;
return this.items.filter(item => {
return item.titre.toLowerCase().indexOf(search.toLowerCase()) > -1
});
}
I hope this helps