push object in array ngFor - arrays

I need to push object in ngFor but I got error Property 'push' does not exist on type 'Observable<MyDataType[]>'.
Stackblitz demo code
HTML
<div *ngFor='let item of myObservableArray | async'>
{{item.value}}
</div>
Component
getData() {
if (!this.myObservableArray) {
this.myObservableArray = this.myService.getData();
this.myObservableArray.push({"id":3, "value":"value_4"});
}
}
Service
mydata: MyDataType[] = [
{"id":1, "value":"value_1"},
{"id":2, "value":"value_2"},
{"id":3, "value":"value_3"}
];
getData():Observable<MyDataType[]>
{
let data = new Observable<MyDataType[]>(observer => {
setTimeout(() => {
observer.next(this.mydata);
}, 4000);
});
return data;
}
}

Demo I added one more method to service to add or update.
addOrUpdate(item:MyDataType){
var elem=this.mydata.find(element=> element.id==item.id);
if(elem){
elem.value=item.value;
}
else{
this.mydata.push(item);
}
}
and call it inside component
this.myService.addOrUpdate({"id":3, "value":"value_4"});

Related

make vuejs component wait for the variable to become available

I have an VueJS component that list the contents of the array to the page. runner.availableResources.cores and runner.availableResources.memory come from bus creates usingbusmq npm package. They take awhile to become available, about 15s depending on IO buffer and thus not immediately available when the page renders.
The error is: [Vue warn]: Error in render: "TypeError: Cannot read property 'cores' of undefined"
How can I make Vue keep checking for values to become available?
<template>
<b-col>
<b-table striped hover :items="formatRunners"></b-table>
</b-col>
</template>
<script>
const fileSize = require("filesize");
export default {
name: "RunnersList",
props: {
runners: Array
},
computed: {
formatRunners() {
const runnerItems = [];
for (const runner of this.runners) {
const newItem = {};
newItem.id = runner.id;
newItem.isPublic = runner.marathon.isPublic;
newItem.AvailableCpu = runner.availableResources.cores;
newItem.AvailableMemory = fileSize(runner.availableResources.memory);
runnerItems.push(newItem);
}
return runnerItems;
}
},
data() {
return {};
}
};
</script>
This is not a really aesthetic solution, but here is a quick workaround:
in your template, add this v-if condition:
<b-table v-if="haveResourcesLoaded" striped hover :items="formatRunners"></b-table>
then in your computed properties, add the corresponding one:
haveResourcesLoaded() {
if (this.runners.length > 0) {
return this.runners[0].availableResources !== undefined
}
return false
}
If you need to do it in a better and more controlled way, you should take a look at the documentation, the bus.isOnline() method might be what you're looking for.
It wasn't so much issue with the listing, as it was update function only getting called once in a minute. The final code is for listing runner is bellow.
<template>
<b-col>
<b-table v-if="runnersTable.length > 0" striped hover :items="runnersTable"></b-table>
</b-col>
</template>
<script>
const fileSize = require("filesize");
export default {
name: "RunnersList",
props: {
runners: Array
},
data() {
return {
haveResourcesLoaded: false
};
},
mounted() {},
computed: {
runnersTable() {
const runnerItems = [];
for (const runner of this.runners) {
const newItem = {
id: runner.id,
isPublic: runner.marathon.isPublic,
AvailableCpu: runner.availableResources.cores,
AvailableMemory: fileSize(runner.availableResources.memory)
};
runnerItems.push(newItem);
}
return runnerItems;
}
}
};
</script>

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

Here is the code below:
component.ts
by selecting match geting id in routing, then taking this id from URL
export class MatchComponent implements OnInit {
_postArrayMatch: match[];
constructor(public router:Router, private matchService: MatchService,
private route: ActivatedRoute) {}
ngOnInit(){
this.getMatchId();
}
getMatchId() :void {
this.route.params.forEach((params: Params)=> {
let id = +params['id'];
this.matchService.getMatch(id).subscribe(
resultArray => this._postArrayMatch = resultArray,
error => console.log("Error ::" + error))
})
}
component.html
just basic interpolation by doing ngFor loop
<div *ngFor="let post of _postArrayMatch">
<p>{{post.team1.name}}</p>
</div>
service.ts
passing the dynamic id
getMatch(id:number): Observable<match[]>{
return this.http.get<match[]>(`http://localhost:3000/match/${id}`)
}
interface
export interface match{
team1:{
name:string,
id:number
}
team2:{
name:string,
id:number
}
}
Try something like this where you create the object in your response
component.ts
export class MatchComponent implements OnInit {
_postArrayMatch: match[];
newArr: Array<Object> = [];
constructor(public router:Router, private matchService: MatchService,
private route: ActivatedRoute) {}
ngOnInit(){
this.getMatchId();
}
getMatchId() :void {
this.route.params.forEach((params: Params)=> {
let id = +params['id'];
this.matchService.getMatch(id).subscribe(
resultArray => {
this._postArrayMatch = resultArray;
const keys = Object.keys(this._postArrayMatch) // new stuff starts here
for(let i = 0; i < keys.length; i++) {
newArr.push(this._postArrayMatch[keys[i]]);
newArr[i]['team'] = keys[i];
}
},
error => console.log("Error ::" + error))
})
}
And then you can access ALL of your sub objects in your html
Component.html
<div *ngFor="let post of newArr">
<p> {{post.team}}: {{post.name}}</p>
</div>
Currently, with what you have you are hard coding for team 1, and if you want to do that then you shouldn't be using the *ngFor
Thats seems the easiest way i could find on how to get the data from objects.
<div *ngFor="let post of objectKeys(_postArrayMatch.team1)">
<div> Team1: {{ _postArrayMatch.team1[post]}}</div>
</div>
component.ts
objectKeys = Object.keys;

Angular 5 - JSON to "scope" binding to *NgFor

I want to bind the data that i get from my JSON request to the *NgFor to be able to read it out, This is how the data looks like that i get in:
{Id: null, Code: "9348892084", HasInfo: true, Info: Array(26)}
HasInfo:true
Info:
Array(26)
0:{ProductId: 32631, Name: "JNOOS", Image: "http://sd-m-mg", …}
1:{ProductId: 32969, Name: "SWIFT", Image: "http://sd-33087.jpg",…}
2:{ProductId: 32570, Name: "GABIX", Image: "http://sd-c7273.jpg", …}
3:{ProductId: 32473, Name: "MISMA", Image: "http://sd-mt8-8343e4d95.jpg", …}
I was working with AngularJS before and there i made the request as such:
$scope.getAll{
$http({
method: 'Get',
url: "http://URL/" + Code
})
.success(function (data) {
$scope.All = data.Info;
})
No i am moving to Angular5 and i would like to get the same array of information bind to the :
<div *ngFor="let x of info">
{{ x.Name }}
</div>
How would i adjust the below to get the same as above?
export class AppComponent {
readonly ROOT_URL = 'http://url/content/'
constructor(private http: HttpClient) {}
ngOnInit() {
this.getData()
}
getData() {
this.http.get(this.ROOT_URL + 'Getscope')
.subscribe(
data => {
var test = data;
// var info = data.Info = not valid!;
// var test can't be approached by *ngFor
console.log(test);
console.log(test.info);
//$scope.info = data.Info;
//this.info = data;
}, error => {
console.error("HTTP FAILURE ERROR!!!");
}
)
};
}
Also the json output has an array inside an object, do i say this correct?
From your code you are using info in html but not assigning to any class variable,
Take a public variable public info; and assign data using this.info = data.Info
Component:
export class AppComponent {
readonly ROOT_URL = 'http://url/content/'
public info;
constructor(private http: HttpClient) {}
ngOnInit() {
this.getData()
}
getData() {
this.http.get(this.ROOT_URL + 'Getscope')
.subscribe(
data => {
this.info = data['Info']; // here is the change
}, error => {
console.error("HTTP FAILURE ERROR!!!");
}
)
};
}
Your HTML can be same:
<div *ngFor="let x of info">
{{ x.Name }}
</div>
The simplest solution would be to use an async pipe. This way you do not need to subscribe to the stream returned by http.get.
app.component.ts
import { Observable } from 'rxjs/Observable';
import { map } from 'rxjs/operators';
export class AppComponent {
readonly url = 'http://url/content/'
constructor(private http: HttpClient) {}
info$: Observable<any[]>;
ngOnInit() {
this.info$ = this.http.get(this.url + 'Getscope')
.pipe(map(resp => resp.Info));
}
}
app.component.html
<div *ngFor="let x of info$ | async">
{{ x.Name }}
</div>

Iterate over data() returned value

My HTML code is like below
<ul>
<li v-for="item in values">{{ item }}</li>
</ul>
My vue.js code is like below
export default {
data() {
return {
values: {}
}
},
props: ['applicants', 'pageinfo'],
watch: {
applicants (val) {
EventBus.$on('click', function (skillName) {
this.values = val[0];
console.log(this.values); // I am getting output here.
});
},
},
}
I am trying to iterate over the values of val[0]. But I am not getting any output.
Either use arrow function like
applicants (val) {
EventBus.$on('click', (skillName) => {
this.values = val[0];
console.log(this.values); // I am getting output here.
});
},
or save the reference of this before the event handler
applicants (val) {
var _self = this;
EventBus.$on('click', function (skillName) {
_self.values = val[0];
console.log(this.values); // I am getting output here.
});
},

How to turn an [object Object] into an array?

I'm displaying some values from an API call into an ngFor directive. I'm trying to convert the data into an array. This is what i get from the server :
Data from the server
I subscribe the data like this :
onVideoClick(video_id) {
this._dashboardService.getVideoData(video_id)
.subscribe(videoData => {
if (videoData.ok) {
console.log(videoData.json());
this.videoData = videoData.json();
} else {
console.log('pas de données vidéos');
}
});
}
I display my data this way :
<tr>
<th *ngFor="let vD of videoData">{{vD.attr_libelle}}</th>
</tr>
How turn this Object into an array ?
You could implement a custom pipe for this. Here is a sample one that creates an array from object entries:
#Pipe({name: 'keys'})
export class KeysPipe implements PipeTransform {
transform(value, args:string[]) : any {
let keys = [];
for (let key in value) {
keys.push({key: key, value: value[key]);
}
return keys;
}
}
and use it like that:
<span *ngFor="#entry of content">
Key: {{entry.key}}, value: {{entry.value}}
</span>
Don't forget to add the pipe into the pipes attribute of the component where you want to use it.
I would use the library Lodash for this conversion.
onVideoClick(video_id) {
this._dashboardService.getVideoData(video_id)
.subscribe(videoData => {
if (videoData.ok) {
console.log(videoData.json());
this.videoData = _.values(videoData.json());
} else {
console.log('pas de données vidéos');
}
});
}
For documentation see here.

Resources