Angular show Success Message of Submit in other Route - json

I do a http post with a header. After this Post I navigate to a List of Customers and want to show SuccesMessage that Entry is included. How can I display message on other route?
Here is my Code:
postData({
let url = "api.url"
var header = new HttpHeaders .... // etc.
this.http.post(url, { company: this.form.value.company }, { headers (header)}).toPromise().then((data: any) => { console.group(data) })
After post route to page an show message:
this.router.navigate(['customer']);
this.showMsg = true;
Here is my html
<div *ngIf="showMsg">Success</div>
But no success message is shown. Why? And what do I have to do? Thank you so much for help!

You need to use a data sharing entity such as a service. For example you could have a service containing this:
private msgSubject: BehaviorSubject<void> = new BehaviorSubject<void>(void 0);
public msg$: Observable<void> = this.msgSubject.asObservable();
showMsg(): void {
this.msgSubject.next();
}
then in the component you navigate to after redirection you just have to inject the service and then subscribe to the observable msg$:
this.msgService.msg$.subscribe(() => (this.showMsg = true));
You will also need to call the showMsg method of the service once your post is successful.

Related

send data when routing angular 6

i want to show a message in my authentification page when my token expires.
the app has a guard that checks in every request if user is still authenticated or not(token is still valid or not).
my problem is when i used localstorage and session storageto store the variable "expired". expired has always true since it's stored in the navigator. Any other solutions?
I am new to angular so please any help ?
what i want to show in my login page if expired is true:
<span *ngIf="expired" class="help-block text-danger">
Votre session a expiré !
</span>
and here is the guard code :
#Injectable()
export class AuthGuard implements CanActivateChild {
constructor(private router: Router, private localSt:
LocalStorageService, private loginService: LoginService) {
}
canActivateChild(childRoute: ActivatedRouteSnapshot, state:
RouterStateSnapshot) {
if (this.loginService.isAuthenticated()) {
sessionStorage.setItem("expired", 'false');
return true;
}
sessionStorage.setItem("expired", 'true');
this.router.navigate(['/login']);
return false;
}
}
what I do to show "The session has expired" is:
If the user is idle, or navigating to a URL without the proper permissions I send him/her to the login page through a function on a shared service
endSesion( message ) {
window.localStorage.clear(); //to clear all session variables, tokens and stuff
window.localStorage.setItem('message',message) // save as the only left thing in LS
this.router.navigate(['login']);
}
And in the constructor or the ngOnInit of the login component
ngOnInit() {
this.message = window.localStorage.getItem('message'); // get the message from LS
if ( this.message ) {
alert('Dude!: ' + this.message ); //maybe sweetalert will be nicer to look at
}
}
This way you dont only use to throw user out beacuse a session expired but maybe if not permission or maybe if you check another security issue even froma backend response.

ANGULAR 6 http get JSON

I am having trouble getting information from certain json file.
case 1 (works):
service:
private xmlToJson: string = 'https://rss2json.com/api.json?rss_url=';
getImg(Url: string) {
return this.http.get(this.xmlToJson + Url);
}
component:
private url='https://api.flickr.com/services/feeds/photos_public.gne';
public images: any = [];
this.imgDataService.getImg(this.url)
.subscribe(data => this.images = data);
HTML:
<h1>{{images.feed.title}}</h1>
case 2 (does not work):
service:
getImg(Url: string) {
return this.http.get(Url);
}
component:
private url = 'https://api.flickr.com/services/feeds/photos_public.gne?format=json&nojsoncallback=1';
public images: any = [];
this.imgDataService.getImg(this.url)
.subscribe(data => this.images = data);
HTML:
<h1>{{images.title}}</h1>
Any idea why case 2 doesn't work? I ran both JSONs here: https://jsonlint.com/ and they came out valid.
You have a CORS error.
Here is a StackBlitz showing the two calls and what is returned from the server. The call for the Flickr URL fails because the Flickr API doesn't (at least on this service) return headers for Access-Control-Allow-Origin to enable public access.
Ironically, you'll be able to call the web service from any code that is not running in a web browser.
Since you probably won't be able to convince them otherwise (others have tried), I would suggest you give up on Flickr.
A final note: You would be able to see the error if you opened your browser's developer tools and checked the console. That should be your first stop for any weird behaviour you encounter in web development.
Change the public images: any = []
to public images: any = {}
Images data isn't an array.
Instead of this.imgDataService.getImg(this.url) type this.imgDataService.getImg(this.url2)
you can try this approach if you know what kind of json response is expected then probably you can create class like
Example:
export class ImageModel{
name:string;
title:string;
src:string;
}
where name,title and src are json keys
then in you can do:
constructor(private httpService:HttpService){}
getImg(Url: string) {
return this.httpService.get<ImageModel>(
(image:ImageModel) => {return image}
}
new HttpService should automatically map your json data to the javascript class/Interface
and then you can read the image to get the json data.

Angular http post not working 1st time, but works on 2nd time

Trying my first angular exercise. Receiving undefined value on 1st time from http post, but 2nd time getting proper response (Edge, Firefox). Thanks!
LoginService (Calls Http post method and returns observable)
login(loginRequest: LoginRequest){
console.log("LoginService.login - userName " + loginRequest.username);
let options = new RequestOptions({ headers: headers });
return this.http.post(this.http_url, loginRequest, options).map( res =>
res.json());
LoginFormComponent (calls service class and convert JSON to typescript object)
onSubmit() {
this.loginSvc.login(this.loginRequest).subscribe(
data => this.loginResponseStr = data,
error => alert(error),
() => console.log('Request completed')
);
var loginResponse = new LoginResponse();
loginResponse.fillFromJSON(JSON.stringify(this.loginResponseStr));
console.log(loginResponse.status);
console.log(loginResponse.statusDesc);
if(loginResponse.status == "SUCCESS"){
this.router.navigate(['/home-page']);
}
Console log
LoginService.login - userName admin main.bundle.js:370:9
undefined main.bundle.js:266:9
undefined main.bundle.js:267:9
Request completed main.bundle.js:263:181
LoginService.login - userName admin main.bundle.js:370:9
SUCCESS main.bundle.js:266:9
VALID USER main.bundle.js:267:9
Request completed main.bundle.js:263:181
Angular server calls are asynchronous, that mean the code wont wait for the server to respond before executing the rest of the code. Such as PHP. So you would not see a blank page waiting for the server to send data. When you want to deal with the respose come from a server call you have to add all the code within the subscribe; that means if this information needed to be passed to another service.
Your code should look like this.
onSubmit() {
this.loginSvc.login(this.loginRequest).subscribe(
data => {
this.loginResponseStr = data
var loginResponse = new LoginResponse();
loginResponse.fillFromJSON(JSON.stringify(data));
console.log(loginResponse.status);
console.log(loginResponse.statusDesc);
if (loginResponse.status == "SUCCESS") {
this.router.navigate(['/home-page']);
}
},
error => alert(error),
() => console.log('Request completed')
);
}

JSON from API call does not show in HTML part

Hello fellow Programmer,
we have an component which loads after clicking on a link, this components content depends on the the link its got clicked. For Example we click on the Link and load a JSON from an API which contain the Data, this Data is shown on our HTML template.
So far we have an succesfull API call which gets us the JSON and we bind it on an var which is conected to the HTML by {{var}}, but it wont display the JSON at all.
We are pretty sure it is a problem with the asynchron call from the API to get the Data, but we have no idea how to fix this.
component.service.ts with the getVoucher() method
getVoucher() {
let voucherUrl = 'xxx'; // URL to web api
let headers = new Headers();
headers.append('Content-Type', 'application/json;charset=UTF-8');
headers.append('Authorization', 'Basic '+btoa("xxx"));
let options = new RequestOptions({ headers: headers });
return this.http.get(voucherUrl,options).map(response => response.json());
}
component.ts
private gutschein;
private strGutschein;
ngOnInit(): void {
this.voucherService.getVoucher().subscribe(data => {
this.gutschein = data;
console.log(this.gutschein);
});
setTimeout(() => console.log(this.gutschein), 2000);
//console.log(this.gutschein);
this.strGutschein = JSON.stringify(this.gutschein);
}
and the HTML Part component.html
{{strGutschein}}
your component code should be like this
private gutschein;
private strGutschein;
ngOnInit(): void {
this.voucherService.getVoucher().subscribe(data => {
this.gutschein = data;
console.log(this.gutschein);
this.strGutschein = JSON.stringify(this.gutschein);
console.log(this.strGutschein);
});
setTimeout(() => console.log(this.gutschein), 2000);
}
and in html part use
{{ strGutschein | json }}

Receiving JSON-Data via http: empty response

I'm new to Angular2 and somehow it's really hard to me to understand how http works in Angular2. I made a simple component which should display a json response. It doesn't work and I have no idea why. I checked many tutorials and tried it with promises as well as observables. Doesn't work. I just can't get the data of the response.
My code:
private doAction() {
this.doHttpRequest().subscribe(
data => this.content = data
);
this.content = JSON.stringify(this.content);
}
private doHttpRequest() {
return this.http.get('http://jsonplaceholder.typicode.com/posts/1')
.catch(this.handleError);
}
this.content is bind to my template. When I click a button to start doAction() for a second I see "" in the template, after another second [object Object]
What is the problem here?
That's the expected behavior
private doAction() {
// schedule HTTP call to server and subscribe to get notified when data arrives
this.doHttpRequest().subscribe(
// gets called by the observable when the response from the server aarives
data => this.content = data
);
// execute immediately before the call to the server was even sent
this.content = JSON.stringify(this.content);
}
To fix it change it to
private doAction() {
this.doHttpRequest().subscribe(
data => {
//this.content = data;
this.content = data.json());
});
);
}
If you want code to be executed after data arrived, then you need to move it inside the subscribe(...) callback.
Since http requests are asynchron you have to put all your logic depending on the results of the http call in the subscribe() callback like this:
private doAction() {
this.doHttpRequest().subscribe(
data => {
this.content = data;
// any more logic must sit in here
}
);
}
private doHttpRequest() {
return this.http.get('http://jsonplaceholder.typicode.com/posts/1')
.map(res => res.json());
.catch(this.handleError);
}
Http call is returning data since it shows "[object Object]" in template. If you want to see the json data in template you can use the json pipe as below.
{{content | json}}
PS: No need of "this.content = JSON.stringify(this.content);" in your code.