I have an angled application where I am trying to perform an insert methods on a backend. I need that after the response of the backend display an alert like for example the one of SweetAlert. But I do not know any components that do this. SweetAlert works at the click of a button, not the response of a backend.
For exemple:
My real question is:
How do I enable SweetAlert in typescript
Can anybody help me?
Make a http request and subscribe it in you desired component and on success of http request, as you get response- show alert.
service.ts
import { Injectable } from '#angular/core';
import { HttpClient, Response, RequestOptions, Headers } from '#angular/http';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/catch';
import 'rxjs/add/observable/throw';
export class CcDataServiceService {
constructor(private http: HttpClient) { <-- httpclient for angular6
}
getData(): Observable<any[]> {
return this.http.get('https://')
.map(this.extractData)
.catch(this.handleError);
}
private extractData(res: Response) {
const body = res.json();
return body || [];
}
private handleError(error: any) {
const errMsg = (error.message) ? error.message :
error.status ? `${error.status} - ${error.statusText}` : 'Server error';
console.error(errMsg);
console.log('Server Error!');
return Observable.throw(errMsg);
}
}
component.ts
import swal from 'sweetalert'
constructor(public jsonDataService: CcDataServiceService) {
}
ngOnInit() {
let thisx = this;
this.jsonDataService.getData().subscribe(
function (success) {
// alert here on success
swal("Hello world!");
},
error => console.log('Getting Server Data Error :: ' +
JSON.stringify(error)));
}
Link:- https://stackblitz.com/edit/angular6-7scyt7?file=app/app.component.ts
Related
I wrote PUT and DELETE methods inside their functions ("editForm" and "deleteForm" respectively).
I wanted to display setAlert() function after each request successfully completes. therefore, I used .then() method and it works perfectly inside editForm function as you can see it below.
but when I do the same for deleteForm, .then() method does not works, because
it says: " Property 'then' does not exist on type 'Subscription' ". So how can I solve this?
Here is my component.ts file:
import { Component, OnInit, OnDestroy } from '#angular/core';
import { ActivatedRoute, Router } from '#angular/router';
import { FormService } from './forms.service';
import { HttpClient } from '#angular/common/http';
import { alert } from './alert';
#Component({
selector: 'app-forms',
templateUrl: './forms.component.html',
styleUrls: ['./forms.component.css']
})
export class FormsComponent implements OnInit {
alert: alert;
id: any;
posts: any;
constructor(public formService: FormService ,private route: ActivatedRoute,
private router: Router, private http: HttpClient) { }
ngOnInit() {
this.id=this.route.snapshot.params['id'];
this.alert = new alert();
this.posts = this.formService.getForms(this.id).subscribe(
(forms: any) => {
this.formService.form = forms[0];
}
);
}
editPost() {
this.formService.editForm().then((res:any) => {
this.formService.alert.setAlert("Post has been successfully saved !");
})
}
deletePost() {
this.formService.deleteForm().subscribe(
data => {
console.log("DELETE Request is successful ", data);
},
error => {
console.log("Error", error);
}
).then(() => {
this.formService.alert.setAlert("Post has been successfully deleted !");
})
}
}
Here is my service.ts file:
import { Injectable } from '#angular/core';
import { HttpClient } from '#angular/common/http';
import { form } from './form-interface';
import { alert } from './alert';
#Injectable({
providedIn: 'root'
})
export class FormService {
formsUrl = "https://jsonplaceholder.typicode.com/posts";
form: form = {
id: 0,
userId: 0,
title: '',
body: ''
};
alert: alert;
constructor(private http: HttpClient) {
this.alert = new alert();
}
getForms(id) {
return this.http.get('https://jsonplaceholder.typicode.com/posts'
+ "?id=" + id)
}
editForm() {
return fetch(this.formsUrl + "/" + this.form.id, {
method: 'PUT',
body: JSON.stringify(this.form),
headers: {
"Content-type": "application/json; charset=UTF-8"
}
})
.then(response => response.json())
}
deleteForm() {
return this.http.delete(this.formsUrl + "/" + this.form.id);
}
}
The editform method uses JavaScript fetch api to call the service, which returns the promise so then method works there. In deleteForm method, you are making a service call using angular HttpClient which returns observable. instead of using then you should use subscribe method
deleteForm() {
return this.http.delete(this.formsUrl + "/" + this.form.id);
}
In your component.ts
deletePost() {
this.formService.deleteForm().subscribe(
data => {
console.log("DELETE Request is successful ", data);
this.formService.alert.setAlert("Post has been successfully deleted !");
},
error => {
console.log("Error", error);
}
)
}
because http returns observable not promise. Use .subscribe here.It will solve your problem
You can use message when you get a proper response while you get the response in subscribe method and call alert into it
Like below
deletePost() {
this.formService.deleteForm().subscribe(
data => {
console.log("DELETE Request is successful ", data);
this.formService.alert.setAlert("Post has been successfully deleted !");
},
error => {
console.log("Error", error);
}
))
}
I am completely new to Angular and I've created a project using SpringBoot 2.0.5.RELEASE, Angular 5 and spring data to build an end to end single page java web application. I use spring boot 1.5 to expose REST APIs and angular5 with routing to build the client that will consume the APIs exposed by the server.
I've defined this component:
import { Component } from '#angular/core';
import { Router } from '#angular/router';
import { User } from '../models/user.model';
import { UserService } from './user.service';
#Component({
templateUrl: './add-user.component.html'
})
export class AddUserComponent {
user: User = new User();
constructor(private router: Router, private userService: UserService) {
}
createUser(): void {
alert ('lala');
this.userService.createUser(this.user)
.subscribe( data => {
alert('User created successfully.');
});
}
}
in the page I can see the alert lala, but not 'User created successfully.' but I have no idea why
The link address when I create a user is this is this one http://localhost:4200/api/users
This is my proxy.config.json file:
{
"/api/*": {
"target": "http://localhost:8080/user-portal",
"secure": false
}
}
and from curl is fine :
curl -X POST -H "Content-Type: application/json" "http://localhost:8080/user-portal/api/users"
and user.service.ts:
import {Injectable} from '#angular/core';
import { HttpClient, HttpHeaders } from '#angular/common/http';
import { User } from '../models/user.model';
const httpOptions = {
headers: new HttpHeaders({ 'Content-Type': 'application/json' })
};
#Injectable()
export class UserService {
constructor(private http: HttpClient) {}
private userUrl = '/api/users';
public getUsers() {
return this.http.get<User[]>(this.userUrl);
}
public deleteUser(user) {
return this.http.delete(this.userUrl + '/'+ user.id);
}
public createUser(user) {
return this.http.post<User>(this.userUrl, user);
}
}
Firstly, best not to use alert. Use console.log. Secondly, you are only handling success, you are not handling failure. Do this:
createUser(): void {
console.log('lala');
this.userService.createUser(this.user)
.subscribe(data => {
console.log('User created successfully', data);
},
err => {
console.log('There was an error', err);
},
() => {
console.log('I have completed now and nothing will ever be emitted from this Observable again');
});
}
The error handler will be executed if the HTTP response is not a success response, viz if the status code of the response is not in the 2xx range.
Check your browser network tab also to see if the HTTP request is failing.
You prob also want to debug this:
public createUser(user) {
console.log('userUrl', this.userUrl)
console.log('user', user)
return this.http.post<User>(this.userUrl, user);
}
To make sure all is as expected.
In Chrome hit F12 to open the dev tools and go to the network tab. Make sure that a request is being made to the end point and that it is not throwing and error.
I am trying to send any errors, exceptions that Angular is catching to my server. I made my own class called GlobalErrorHandler that is extending ErrorHandler. Please check below
import { ErrorHandler, Injectable, Injector } from "#angular/core";
import {HttpHeaders, HttpClient} from "#angular/common/http";
import { TestServiceService } from "../_services/test-service.service";
#Injectable()
export class GlobalErrorHandler implements ErrorHandler {
constructor(
private injector: Injector,
private http: HttpClient,
private service: TestServiceService,
) {}
url = 'http://127.0.0.1:4000/post';
handleError(error) {
const httpOptions = {
headers: new HttpHeaders({'Content-Type': 'application/json'})
};
try {
let msg = JSON.parse(error)
console.log('>>>>>>>>> message is ', msg)
this.http.post(this.url, msg, httpOptions);
}
catch (e) {
console.log('>>>>>>>>> err in catch is ', e)
}
}
}
I am able to console.error(error) whenever an error occurs, but I cannot make a post request to my server.
What am I missing in my code to make post request from ErrorHandler?
After changing the code to the following (replacing JSON.parse with JSON.stringify and catching the post errors successfully):
handleError(error) {
const httpOptions = {
headers: new HttpHeaders({'Content-Type': 'application/json'})
};
let subscription = this.http.post(this.url, JSON.stringify(error), httpOptions).subscribe(
(data => {console.log('>>>>>>> data is ', data));subscription.unsubscribe();},
error => {console.log('>>>>>>>> err', error);subscription.unsubscribe();}
)
}
The error was discovered to be on the serverside, but the code above should be useful to anyone trying to trasmit clientside errors(in Angular2+) to the server provided that the server has been implemented correctly.
Hell
I ma new in angular 5. I am create a login and auth service. But i cannot compile my code. Here is my code
// user.service.ts
import { Injectable } from '#angular/core';
import { Http, Headers } from '#angular/http';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/map';
#Injectable()
export class UserService {
private loggedIn = false;
constructor(private http: Http) {
// this.loggedIn = !!localStorage.getItem('auth_token');
}
//authenticate user with dummy logic because i use a json-server
authenticate(login:string, password:string) {
console.log('Authenticate ....');
const credentials = {login:login, password:password};
let headers = new Headers();
headers.append('Content-Type', 'application/json');
var result = this.http
.get(
'/users?login?'+JSON.stringify(login),
{ headers }
);
if(result.password==password){
return true;
}
return false;
}
}
When i compile ( ng server ) i get the following error
ERROR in src/app/auth/user.services.ts(28,17): error TS2339:
Property 'password' does not exist on type 'Observable<Response>'.
Line 28 is : if(result.password==password){
I don't know what i am missing ?I try to understand the Observable concept. If you add an idea, it will help me.
Thanks
result here is an observable, you need to subscribe to it to get response.
Something like below:
var result = this.http.get(
'/users?login?'+JSON.stringify(login),
{ headers }
);
//result is an observer here, you have to subscribe to it
result.subscribe((response) => {
if(response.password==password){
return true;
}
return false;
});
You can check this awesome article: https://gist.github.com/staltz/868e7e9bc2a7b8c1f754
Use Observables properly
Use HttpClient, not old Http
You can also define a User class to make typing more strict.
// user.service.ts
import { Injectable } from '#angular/core';
import { HttpClient } from '#angular/common/http';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/map';
#Injectable()
export class UserService {
private loggedIn = false;
constructor(private http: HttpClient) {
// this.loggedIn = !!localStorage.getItem('auth_token');
}
//authenticate user with dummy logic because i use a json-server
authenticate(login:string, password:string) :Observable<boolean> {
return this.http
.get('url/whatever') //returns a User object having password
.map(user => user.password === password); // maps result to the desired true or false value
}
}
// to consume the service from a component, for example
this.userService.authenticate('myusername', 'mypassword')
.subscribe(authenticated => {
console.log('login status', authenticated)
})
You are trying to access the observable returned from the http call.
To get the information in the observable you have to subscribe to it.
For detailed information about hot to get remote data please read this:
https://angular.io/guide/http
NOTE: You should not use the deprecated angular/http. Use angular/common/http instead.
This question already has answers here:
How to access the correct `this` inside a callback
(13 answers)
Closed 5 years ago.
Now I am trying to use Angular2 Router.navigate, but it isn't working.
import { Injectable } from '#angular/core';
import { Http, Headers } from '#angular/http';
import { Router } from '#angular/router';
import { Observable } from 'rxjs/Observable';
import 'rxjs/Rx';
#Injectable()
export class HttpService {
constructor(
public _http: Http,
public _router: Router
)
{
}
public sendPostRequestWithParams(url, params) {
let headers = new Headers();
headers.append('Content-Type', 'application/x-www-form-urlencoded');
return this._http.post(url, params, {headers: headers})
.map(res => res.json())
.catch(this.handleServerError);
}
public handleServerError(error: Response) {
let jError = error.json() && error.json()['error'];
if (jError == 'Unauthenticated.') {
alert("You are not unauthenticated. Please login correctly!");
this._router.navigate(['login']);
return Observable.throw("You are not unauthenticated. Please login correctly!");
}
return Observable.throw(error.json() || 'Server error'); // Observable.throw() is undefined at runtime using Webpack
}
}
But when calling handleServerError, it shows error "Cannot read property navigate of undefined".
Is it impossible to use Router in Service?
Change below line
this._router.navigate(['login']); => this._router.navigate(['/login']);