Ionic rxjs pipe function not getting called after http post - firebase

I am using ionic 5
when I try to connect to firebase using post and get the response data and process the response using pipe and tap then it's not working. The log is not printing.
But when I replace the pipe with subscribe then it's working correctly and I can see the log correctly.
Please see the working and not working code below.
Can someone please help me to solve this issue. Thanks for your help.
WORKING CODE
return this.http.post("https://project-name.firebaseio.com/offered-places.json", {
...newPlace,
id: null
}).subscribe(resDate => {
console.log(resDate);
});
NOT WORKING CODE
return this.http.post("https://project-name.firebaseio.com/offered-places.json", {
...newPlace,
id: null
}).pipe(
tap(resData => {
console.log(resData);
})
);

As stated in comments you have to call subscribe method
Here's the snippet which reproduces your cases and provides mentioned solution.
const exampleObservable1 = rxjs.of([{}]);
const exampleObservable2 = rxjs.of([{}]);
const exampleObservable3 = rxjs.of([{}]);
console.log('working example');
exampleObservable1.subscribe(resDate => {
console.log(resDate);
});
console.log('not working example');
exampleObservable2.pipe(
rxjs.operators.tap(resData => {
console.log(resData);
}))
console.log('suggestion');
exampleObservable3.pipe(
rxjs.operators.tap(resData => {
console.log('tap', resData);
})).subscribe(resDate => {
console.log('subscription', resDate);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/rxjs/6.5.5/rxjs.umd.js"></script>

Related

Unable to use array's method "find" in Vue 3

I am trying to get current location of a user and then push it into array. Before I do so, I check whether a city with the same name is already there. In that case, I won't push it into the array. However, when I am trying to check it, it says: Uncaught (in promise) TypeError: Cannot read properties of null (reading 'find').
const found = ref(false);
const weatherResponse = ref([]);
function getLocation() {
console.log("SETTING LOCATION");
navigator.geolocation.getCurrentPosition((position) => {
console.log(`Lat: ${position.coords.latitude}, Lon: ${position.coords.longitude}`);
if (position.coords.latitude && position.coords.longitude) {
axios.get(`https://api.weatherapi.com/v1/current.json?key=${API_KEY}&q=${Math.round(position.coords.latitude)},${Math.round(position.coords.longitude)}&aqi=no`)
.then((response) => {
found.value = weatherResponse.value.find((item) => item.location.name == response.data.location.name);
if (response.data?.error?.code != 1006 && !found.value) {
weatherResponse.value.push(response.data);
this.$store.commit("addToList", response.data);
console.log(weatherResponse.value);
}
})
}
},
(error) => {
console.log(error.message);
}
)
}
I've already tried using fetch, axios to grab the API, but the "find()" method is still not working. Regarding "found" variable, I tried using it in ref as well as declaring it as "let found".
After trying and testing, I've finally managed to get everything to work. My issue was in (weirdly) main.js. Because it was set out like this: createApp(App).use(cors, store).mount('#app') it, I guess, caused VueX.store not to load in properly because mounted hook was called and it was throwing all sorts of mistakes. Putting it like const app = createApp(App); app.use(store); app.use(cors); app.mount("#app"); actually made it work.

newbie question - firebase svelte-infinite-loading - unable to read new data from firestore

I'm trying to load db content on scroll down, but i'm getting errors because i don't know how to read correctly the data. Error shows that there is no data.hits, is undefined. What that means?
I used this sample: svelte-infinite-loading sample and tried to apply to work with firebase, but I don't know how to read the console.log(data), hits is undefined, but should it be?
Could someone help me?
ContentBlocks.svelte
<script>
import InfiniteLoading from "svelte-infinite-loading";
let page = 1;
function fetchData({ detail: { loaded, complete } }) {
const response = db
.collection("todos")
.orderBy("created", "desc")
.startAfter(page*5)
.limit(5);
response.get().then((data) => {
console.log(data)
if (data.hits.length) {
page += 1;
list = [...list, ...data.hits];
loaded();
} else {
complete();
}
});
}
</script>
<Box>
<InfiniteLoading on:infinite={fetchData} />
</Box>
is use async / await but that will still help you (also, your list variable is not declared anywhere we can see):
const results = await queryObj.get(); // queryObj == your response constant
if (results.docs) {
list.concat(results.docs.map((doc) => doc.data()));
}
doc is here, with another solution to that problem : https://firebase.google.com/docs/firestore/query-data/get-data#get_multiple_documents_from_a_collection

Chat in Ionic with Cloud Firestore

I'm trying to implement a chat page in my app.
In the constructor I ask for all the messages in the database:
this._DB
.getDocument("chats", this.favour.chatId)
.then(documentSnapshot => {
var chat = documentSnapshot.data();
for (var key in chat) {
chat.key = chat[key];
}
delete chat.key;
this.chat = chat;
})
.catch(error => {
console.log(error);
});
And the app load ok the messages with this html:
<ion-item *ngFor="let messages of chat?.messages" class="chat" text-wrap [ngClass]="{'chat-partner' : messages?.askedName == localStorage?.name}">
{{messages.message}}
</ion-item>
To implemet a real time chat I see in the docs I have to use the onSnapshot method:
https://firebase.google.com/docs/firestore/query-data/listen
Then I use this function:
ionViewDidEnter() {
this._DB._DB
.collection("chats")
.doc(this.favour.chatId)
.onSnapshot(function(doc) {
this.chat = doc.data();
console.log(this.chat);
});
this.content.scrollToBottom();
}
But the problem is that this.chat is showed ok in the console by the console.log, but the html dont refresh it :-(
I'm doing something wrong?
Thanks in advance
PS: I see maybe is confuse in the onSnapshot function I use this._DB._DB, this is because in the provider (the _DB) I don't have that functiĆ³n and I make it public to can use in other place and can do tests.
Finally I find a solution.
Looks like the problem is the object this... is diferent in the component like in the function called by onSnapshot.
I solved creating a different function:
observingChat(objectThis){
if(objectThis.favour.chatId){
this._DB._DB
.collection("chats")
.doc(objectThis.favour.chatId)
.onSnapshot(function(doc) {
objectThis.chat = doc.data();
objectThis.content.scrollToBottom();
});
}
}
That recibe the object this, and call it from the ionViewDidEnter()
ionViewDidEnter() {
this.content.scrollToBottom();
this.observingChat(this);
}
I don't know why or where the object this change.... if anybody can clarify and say me if the solution is correct I will be vefry gratefull :-)

WooCommerce.getAsync API not working return value

I try to many times but not return value inside nested function. I am using WooCommerce REST API inside a ionic 2 project, This API response successfully but that response not return. Please resolve my issue. I am stuck so many time and i have not any solution. Please help me :(
I am using this plugin WooCommerce API - Node.js Client
Sorry for my English. Please try to understand. ThankYou
ionViewDidLoad() {
this.woocom().then((result) => {
console.log('result===='+result);
});
}
woocom(){
var WooCommerceAPI = require('woocommerce-api');
var WooCommerce = new WooCommerceAPI({
url: 'http://test.com',
consumerKey: 'ck_xxxxxxxxxxxxxxxxxxxxxxxxxx',
consumerSecret: 'cs_xxxxxxxxxxxxxxxxxxxxxxxx'
});
WooCommerce.getAsync('products/categories').then((result) => {
console.log(result.toJSON().body);
//return Promise.resolve(JSON.parse(result.toJSON().body));
// return JSON.parse(result.toJSON().body);
});
return Promise.resolve();
}
Try this
WooCommerceResult:any=[];
WooCommerce.getAsync('products/categories').then((result) => {
console.log(result.toJSON().body);
this.WooCommerceResult=result.toJSON().body;
//return Promise.resolve(JSON.parse(result.toJSON().body));
// return JSON.parse(result.toJSON().body);
});
Bind WooCommerceResult using *nFor in a view

Using pipe in *ngFor, the page sometimes updates, sometimes not

I am using angular2-meteor, I already use pure: false. But the pipe sometimes run, sometimes not. See my comments in the code for details of the problem.
Thanks
<div *ngFor="#user of (users|orderByStatus)">
{{user.status.online}}
</div>
users:Mongo.Cursor<Meteor.User>;
ngOnInit()
{
this.subscribe('users', () => {
this.autorun(() => {
this.users = Meteor.users.find();
});
}, true);
}
import {Pipe} from 'angular2/core';
#Pipe({
name: 'orderByStatus',
pure: false
})
export class OrderByStatusPipe {
transform(usersCursor:Mongo.Cursor<Meteor.User>):Array<Meteor.User> {
console.log("OrderByStatusPipe runs");
// (1) If I only do these two lines, the change of other users' status can show on the screen immediately.
// let users = usersCursor.fetch();
// return users;
// (2) If sort users by status, the page sometimes updates, sometimes not when user status change.
// If not update automatically, I click that part of screen, it will update then.
let users:Array<Meteor.User> = usersCursor.fetch();
users.sort((a, b) => {
return (a.status.online === b.status.online) ? 0 : (a.status.online ? -1 : 1);
});
return users;
}
}
UPDATE: The bug seems fixed.
I think the problem is related with angular2-meteor.
At last I found a working way using sort in when you try to get data from Mongo. So not using sort pipe any more.
But you cannot use users:Mongo.Cursor<Meteor.User> with *ngFor, need fetch() first and use Array<Meteor.User>, otherwise it will show this error when the order of list changes:
Cannot read property 'status' of undefined
But then the list won't update automatically in UI. So you need use NgZone.
So the final working code is like this:
<div *ngFor="#user of users)">
{{user.status.online}}
</div>
users:Array<Meteor.User>; // here cannot use users:Mongo.Cursor<Meteor.User>
constructor(private _ngZone:NgZone) {}
ngOnInit()
{
this.subscribe('users', () => {
this.autorun(() => {
this._ngZone.run(() => {
this.users = Meteor.users.find().fetch();
});
});
}, true);
}
I don't know exactly what is behind the calls Meteor.users.find() and usersCursor.fetch() but I think the retrieval of your users should be done outside the filter itself. I guess that one part is done in the filter (with usersCursor.fetch()?) and this could be the problem...

Resources