How to display data from server in angularv8 - node.js

I would like to display the name of the person who logged in the app. I tried this
getprotected() {
return this.http.get(${this.url}/api/protected_things)
.pipe(
catchError(e => {
let status = e.status;
if (status === 401) {
this.showAlert('You are not authorized for this!');
this.logout();
}
throw new Error(e);
})
)
}
tab1.ts
export class Tab1Page implements OnInit {
data = '';
constructor(private authService: AuthService, private storage: Storage, private toastController: ToastController, private http: HttpClient) { }
ngOnInit() {
this.authService.getprotected().subscribe(res => {
this.data = res['name'];
});
}
tab1.html
<p class="ion-text-center">Bienvenu</p>
<p class="ion-text-center"><b>{{ data }}</b></p>
<ion-button expand="full" (click)="logout()">Deconnecte Toi</ion-button>
but ts not working.
thank you

you should try to access the data you need with res.name.
As a general rule of thumb, try logging your result.
A simple console.log(res) from within the .subscribe() will help you visualize the object you receive.
If the problem happens early, the chrome network inspector will help you detect the data you receive. Keep in mind that an empty object will not trigger your catch error. To know more about network tab in chrome: https://www.youtube.com/watch?v=e1gAyQuIFQo&
By the way you should watch some tutorial, on youutbe you can find great material

Related

NestJS websockets - Get client URL and hostname

I am trying to access the hostname of a client in NestJS websockets when a message is received. I have searched here, NestJS docs, and the project Github issues & code but have not found a solution.
I have tried accessing properties on the client object, but the hostname is not included. I was able to find it in the handleConnection subscriber, but I need it in the SubscribeMessage handler.
Would love any help!
Sample of the code from the docs:
export class SessionsGateway
implements OnGatewayConnection, OnGatewayDisconnect
{
constructor() {}
async handleDisconnect() {}
async afterInit(server) {}
#SubscribeMessage('init')
async onInit(
#MessageBody() event,
#ConnectedSocket() client,
) {
try {
// GET THE HOSTNAME HERE
} catch (error) {
console.log(error);
client.close();
}
}

Calling an onCall function in Firebase Functions using AngularFire results in a 404 error, while returning the expected result

I have created a few onCall cloud functions using Firebase. These functions interact with Stripe through the API. When I use AngularFire, or more specifically, AngularFireFunctions to call these said cloud functions, I receive the error message A bad HTTP response code (404) was received when fetching the script. in Chrome developer console. Yet, the expected result is received with no problem and the Firebase console displays a 200 response with no error messages or warnings. The project is entirely hosted on Firebase.
The 404 error also does not display a file that it is connected to in the console as such errors typically do within that console.
UPDATE
I also feel it is relevant to include, the Stripe developer logs in the dashboard reflect no errors, but a successfull call upon checking.
I have also tried to remove the call to Stripe in the cloud function and simply only return a string return 'The customer ID is:'+ ${data.customerId}+'. Thank you.' and still received the same error message.
I have also tried this solution, https://github.com/angular/angularfire/issues/1933#issuecomment-432910986 with the following code being placed inside app.module.ts however, am unable to find where FunctionsRegionToken would be defined to be able to import it.
providers: [
{ provide: FunctionsRegionToken, useValue: 'us-central1' }
]
Although, I'm not sure how changing the region to the same region the function is being called from currently would make any difference.
When you explore the Network tab of the developer console and visit the page that calls the function, you see that something is trying to call http://localhost:4200/firebase-messaging-sw.js which doesn't exist. The amount of calls to this file and the errors in the console coincide with each other which leads me to believe they are related.
END OF UPDATE
I have tried to add CORS to my cloud function (and am using it in onRequest functions), I've tried rewriting my cloud function, and even tried changing the client side function that calls the onCall to no avail. The only way to remove the error is to remove the call to the function, thus I've narrowed it down to something with the AngularFireFunctions.
What I am using and the versions
Angular V13
Firebase 9.6.7
Angular Fire 7.2.1
Node 16.13.1
What follows is my code, broken up into sections.
Cloud function
const cors = require('cors')({origin: true});
import * as functions from "firebase-functions";
import * as admin from "firebase-admin";
const FieldValue = require('firebase-admin').firestore.FieldValue;
admin.initializeApp();
const firebaseApp = admin.app();
const firebaseDB = firebaseApp.firestore();
const Stripe = require('stripe');
const stripe = Stripe(functions.config().stripe.key);
export const retrieveCustomer = functions.https.onCall( async(data) => {
if(data.customerId) {
const customer = await stripe.customers.retrieve(data.customerId);
if(customer) {
return customer;
} else {
throw new functions.https.HttpsError('unknown', 'An unknown error occurred, please try again.');
}
} else {
throw new functions.https.HttpsError('invalid-argument', 'A customer ID must be provided.');
}
});
Angular Service
import { Injectable } from '#angular/core';
import { AngularFirestore } from '#angular/fire/compat/firestore';
import { AngularFireFunctions } from '#angular/fire/compat/functions';
#Injectable({
providedIn: 'root'
})
export class BillingService {
constructor( private aff: AngularFireFunctions, private afs: AngularFirestore ) { }
RetrieveCustomer(customerId:string) {
const callable = this.aff.httpsCallable('retrieveCustomer');
return callable({
customerId: customerId
});
}
}
Angular Component
import { Component, OnInit, AfterContentInit } from '#angular/core';
import { BillingService } from 'src/app/shared/services/billing/billing.service';
#Component({
selector: 'app-billing-settings',
templateUrl: './billing-settings.component.html',
styleUrls: ['./billing-settings.component.css']
})
export class BillingSettingsComponent implements OnInit, AfterContentInit {
public stripeCustomer!: any;
constructor( private billingService: BillingService ) { }
ngOnInit(): void {
}
ngAfterContentInit(): void {
this.billingService.RetrieveCustomer('cus_LGRX8TPVF3Xh0w').subscribe((customer:any) => {
console.log(customer);
});
}
}

Getting the http post canceled when subscribing from a service

Stuck in this error for a week. Cannot send a simple post request to the heroku server using the Angular HttClient. Defined all the services in the provider section in the main app Module. The Error Handling service is not logging any error after sending the post request(This service works fine that i have tested in another project).
The component is defined in a different module but services are defined and provided in the root app.module.ts
These Modules that components live are imported in the main app module.
But no matter what the post request being canceled!!.
API Params
email: string
password: string
AuthModel
Model using for defining the data params for API
export interface AuthModel {
email: string;
password: string
}
AuthService.ts
This is the service i used to inject into my component.ts file for subscribing. This service also uses another service to handle the error cases HandleError
const httpOptions = {
headers: new HttpHeaders({
'Content-Type': 'application/json',
})
};
#Injectable({
providedIn: 'root'
})
export class AuthService {
signUpUrl = 'myurl';
private handleError: HandleError;
constructor(private http: HttpClient, private httpErrorService: HttpErrorService) {
this.handleError = this.httpErrorService.createHandleError('AuthService'); //Problem lies here
}
signUp(authModel: AuthModel) : Observable<AuthModel>
{
return this.http.post<AuthModel>(this.signUpUrl,authModel,httpOptions).pipe( catchError(this.handleError('signup',authModel)) );
}
}
component.ts
Submit function is called when button is clicked after entering the data
Submit(): void {
this.authModel!.email = this.emailHolder.value;
this.authModel!.password = this.passwordHolder.value;
this.authService.signUp(this.authModel).subscribe((res)=> {console.log(res)});
}
The problem was with my handleError function, it get's canceled not matter the response was. So make sure guys to write a proper errorHandling function, else you will get unintended result.

How to increase increase database attribute by one by making a get request to the database from Reactjs

I am working on Mernstack. I have a model called Events, the Events have a title, description, startingDate, and closingDate attributes. when an Event is created, people can indicate that they are going for the event by clicking a button and this button will update another attribute inside that Event called going by increasing the number by 1. this was working with Node and Expressjs only but now that I am integrating React to Node, I don't know how to make it work.
Now my question is, how do I make a GET request from React to My Express route, by clicking a link so that the going attribute inside the Event model will be increased by one?
Here is my Event route
router.get("/:id/going", async (req, res, next) => {
Event.findById(req.params.id, function(err, event) {
if (!event) {
return next(new Error('Could not load Document'));
}else {
event.going += 1;
event.save();
res.json(event)
}
});
});
and here is my constructor in Reactjs.
Note: my Event and EventComment is working fine, i am only looking for a way to increase the value of going attribute inside the event by 1 whenever a link clicked.
constructor(props) {
super(props);
this.state = {
eventcomments: [],
event: '',
name: '',
description:'',
going: '',
};
}
the GET request i want to use to trigger the event route to increase the number by 1
axios.get('http://localhost:9000/events/'+this.props.match.params.id+'/going')
.then(res => {
this.setState({
going: '',
})
})
and this is the link i want a user to click for the going attribute in the Event route to increase by 1
<Link to={"/events/"+this.state.event._id+"/going"}>Going</Link>
since your endpoint is returning the updated event record with the updated going property, just set state with that value.
axios.get('http://localhost:9000/events/'+this.props.match.params.id+'/going')
.then(res => {
this.setState({
going: res.data.going
})
})
if res.data.going is how the return value is shaped.
Thanks Guys. I have managed to get it to work.
Here is what I did.
updateGoing = going => {
axios.get('http://localhost:9000/events/'+this.props.match.params.id+'/going')
.then(response => {
his.setState({event: response.data})
});
and Changed it from Link to Button
<button onClick={() => this.updateGoing(this.state.event._id)}> Going </button>

How to send Blob image to NodeJs using Angular2?

I am having problems trying to upload a photo from my frontend.
I have an input file where I can select a file from my computer.
What I want It is send that photo to my backend and store it as a Blob.
First I try to get the file and save as Blob:
foto: Blob;
setFoto(event){
this.foto = event.target.files[0];
}
But I don't know if this It is correct.
Second I send "this.foto" to the server using HTTP post and save in my db as blob. I think that my problem is that i am not sending the correct information about the photo.
In resume, what I want is send an image that I select from my computer to the server but I am having problems getting the correct information of the photo.
Solution founded
First, here is my input:
<input type="file" (change)="setFoto($event)">
Second, here is the method that you call when you select a photo.
setFoto(event) {
const foto = new Blob([event.target.files[0]]);
var reader = new FileReader();
reader.readAsDataURL(foto);
reader.onloadend = () => {
this.foto = reader.result;
}
}
this.foto is a string.
Then when i click on update button i send the new photo as url and save it in my db (Mysql) as TEXT.
updateApuesta() {
this.userService.updateBet(this.url, {
id: this.userService.getIdbet(),
coste: this.coste,
beneficio: this.beneficio,
foto: this.foto
}).subscribe(this.success.bind(this), this.error);
}
When I try to get the photo from my server I use this. I call my http get service and get the photo.
First, the new image is a
image: SafeResourceUrl;
and I assign the dat that I got from my server.
this.image = this.sanitizer.bypassSecurityTrustResourceUrl(data.foto);
You have to import:
import { DomSanitizer, SafeResourceUrl } from '#angular/platform-browser';
and pass it to your constructor:
constructor(private sanitizer:DomSanitizer ) { }
So finally, you got your image in this.image that is a SafeResourceUrl type. To load it in a you have to do this:
<img [src]="bet.foto"/>
where in your case bet.foto will be yout this.image that you have to pass to the template.
this.userService.updateBet(
this.url,{foto:this.foto}).subscr‌​ibe(this.success.bin‌​d(this), this.error);
and the service is:
updateBet(url, body) {
return this.httpRequest.put(url, body, this.options);
}
put(url, body, options) {
return this.http.put(url, body, this.setOptions(options))
.map(this.extractData)
.catch((error: any) => Observable.throw(error.json().error || 'Server error')); //Show errors if any
}
But what i said, i think i am not sending the correct info about the photo.

Resources