How can I bind from a callback in Angular 4
.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty{ height:90px;width:728px;box-sizing:border-box;
}
I am trying to bind my template to the value which was returned from subscription via callback. But there is no change detection invoked.
//authorisation service
public login(data,callbackFromLogin : (msg) => void): void {
this.http.httpPost(ApiRoutes.LoginRoute,data).subscribe(result => {
callbackFromLogin(msg);
});
}
//and then in login component
onSubmit(request) {
this.authService.login(request,(message) => {
alert(NgZone.isInAngularZone());
if(message) {
this.ngZone.run( () => {
this.message = message;
alert(NgZone.isInAngularZone());
});
}
});
}
<div>{{message}}</div>
The message does not change, though It gets a value from a service. I guess this issue is related to Zone.
angular typescript asynchronous zone
add a comment |
I am trying to bind my template to the value which was returned from subscription via callback. But there is no change detection invoked.
//authorisation service
public login(data,callbackFromLogin : (msg) => void): void {
this.http.httpPost(ApiRoutes.LoginRoute,data).subscribe(result => {
callbackFromLogin(msg);
});
}
//and then in login component
onSubmit(request) {
this.authService.login(request,(message) => {
alert(NgZone.isInAngularZone());
if(message) {
this.ngZone.run( () => {
this.message = message;
alert(NgZone.isInAngularZone());
});
}
});
}
<div>{{message}}</div>
The message does not change, though It gets a value from a service. I guess this issue is related to Zone.
angular typescript asynchronous zone
could you create a stackblitz snippet for this ?
– Korte
Nov 22 '18 at 22:34
add a comment |
I am trying to bind my template to the value which was returned from subscription via callback. But there is no change detection invoked.
//authorisation service
public login(data,callbackFromLogin : (msg) => void): void {
this.http.httpPost(ApiRoutes.LoginRoute,data).subscribe(result => {
callbackFromLogin(msg);
});
}
//and then in login component
onSubmit(request) {
this.authService.login(request,(message) => {
alert(NgZone.isInAngularZone());
if(message) {
this.ngZone.run( () => {
this.message = message;
alert(NgZone.isInAngularZone());
});
}
});
}
<div>{{message}}</div>
The message does not change, though It gets a value from a service. I guess this issue is related to Zone.
angular typescript asynchronous zone
I am trying to bind my template to the value which was returned from subscription via callback. But there is no change detection invoked.
//authorisation service
public login(data,callbackFromLogin : (msg) => void): void {
this.http.httpPost(ApiRoutes.LoginRoute,data).subscribe(result => {
callbackFromLogin(msg);
});
}
//and then in login component
onSubmit(request) {
this.authService.login(request,(message) => {
alert(NgZone.isInAngularZone());
if(message) {
this.ngZone.run( () => {
this.message = message;
alert(NgZone.isInAngularZone());
});
}
});
}
<div>{{message}}</div>
The message does not change, though It gets a value from a service. I guess this issue is related to Zone.
//authorisation service
public login(data,callbackFromLogin : (msg) => void): void {
this.http.httpPost(ApiRoutes.LoginRoute,data).subscribe(result => {
callbackFromLogin(msg);
});
}
//and then in login component
onSubmit(request) {
this.authService.login(request,(message) => {
alert(NgZone.isInAngularZone());
if(message) {
this.ngZone.run( () => {
this.message = message;
alert(NgZone.isInAngularZone());
});
}
});
}
<div>{{message}}</div>
//authorisation service
public login(data,callbackFromLogin : (msg) => void): void {
this.http.httpPost(ApiRoutes.LoginRoute,data).subscribe(result => {
callbackFromLogin(msg);
});
}
//and then in login component
onSubmit(request) {
this.authService.login(request,(message) => {
alert(NgZone.isInAngularZone());
if(message) {
this.ngZone.run( () => {
this.message = message;
alert(NgZone.isInAngularZone());
});
}
});
}
<div>{{message}}</div>
angular typescript asynchronous zone
angular typescript asynchronous zone
edited Nov 23 '18 at 6:39
fiza khan
1,018521
1,018521
asked Nov 22 '18 at 21:34
Victor RodnianskyVictor Rodniansky
5018
5018
could you create a stackblitz snippet for this ?
– Korte
Nov 22 '18 at 22:34
add a comment |
could you create a stackblitz snippet for this ?
– Korte
Nov 22 '18 at 22:34
could you create a stackblitz snippet for this ?
– Korte
Nov 22 '18 at 22:34
could you create a stackblitz snippet for this ?
– Korte
Nov 22 '18 at 22:34
add a comment |
6 Answers
6
active
oldest
votes
I don't know exactly why this not happen.
But some question below.
Who is set msg
to the callback?
Maybe you want to do callbackFromLogin(result);
?
But I think you could try to implement another solution.
Why you are pass a callback to service and not do the function inside the subscription on the component?
Something like this:
// authorisation service
public login(data) {
return this.http.httpPost(ApiRoutes.LoginRoute, data);
// if you want manipulate the message you could use `pipe` method here
}
// and then in login component
onSubmit(request) {
this.authService.login().subscribe((message) => {
if(message){
this.message = message;
}
});
}
Sorry , for simplicity reasons , I removed some code from the snippet. The message is set after I am getting an error. let msg = "...."; callbackFromLogin(msg); the problem is that I have more logic in a service (in my subscription) I didn't want to move it to the login component, I wanted to send only the messag (msg)
– Victor Rodniansky
Nov 22 '18 at 22:06
You don't need to move the logic to the component, you could use RxJS operators likemap
,tap
, whatever you need and use them to apply your logic in the service. Then, in the subscribe only update the message in the component. I think this is the best practice.
– ptesser
Nov 22 '18 at 22:14
Thank you I changed my code..but still I am getting the same result ..the message is passed , but could not be changed in a binding ({{}}) I will post a new snippet now.
– Victor Rodniansky
Nov 22 '18 at 22:54
add a comment |
I used your advise and change my code to this:
//Service
public login(data): Observable<any> {
return this.http.httpPost(ApiRoutes.LoginRoute,data).pipe(map(result=>{
if (result && result.status == 200) {
///
}else{
let msg = `my message`;
return {msg:msg};
}
}));
}
//login component
onSubmit(request){
this.authService.login(request).subscribe((result) => {
if(result.msg){
this.message = result.msg;
alert( this.message )
}
});
}
<div>{{message}}</div>
Same issue , the message is passed to result ,when I call to alert( this.message ) function , the message is shown above..but there is no change in a template Interpolation however.
I suppose it could be some issue in my app..because I know such code should trigger the change... What could be a reason for this strange behavior.
– Victor Rodniansky
Nov 22 '18 at 23:11
Where are you getting the httpPost() method from? Angular's HttpClient doesn't have a httpPost() method.
– Anjil Dhamala
Nov 22 '18 at 23:17
add a comment |
Yes..here is an AuthService:
import { SessionService } from '../session/session.service';
import { environment } from './../../../environments/environment';
import { IUser, UserType } from '../../../../../contracts/IUser';
import { IEmployee } from '../../../../../contracts/IEmployee';
import { Injectable,Inject } from '@angular/core';
import { Router } from '@angular/router';
import 'rxjs/add/operator/filter';
import * as auth0 from 'auth0-js';
import { Http } from '@angular/http';
import {ReplaySubject, Observable} from 'rxjs/Rx';
import { ApiService } from '../api/api.service';
import { ActivityService } from '../activity/activity.service';
import { UserActivityAction } from '../../../../../contracts/Library';
import { ApiRoutes } from '../../../../../contracts/ApiRoutes';
import { AlertService} from '../alert/alert.service';
import { MessageService} from '../message/message.service';
import {Events} from '../../../../../contracts/Library';
import { map } from 'rxjs/operators';
@Injectable()
export class AuthService {
private userIsLoggedIn : boolean;
constructor(public http: ApiService,private rHttp: Http,
private session:SessionService,
@Inject('BASE_URL') public baseUrl: string,
public router: Router,
private alertService: AlertService,
private activity: ActivityService,
private messageService : MessageService)
{
this.session = session;
}
// logIn attempts to log in a user
handleAuthentication() : void {
let auth = this.http.httpGetAll(ApiRoutes.AuthRoute);
auth.subscribe(
data => {
let results = data.json();
switch(results.status) {
case 401: {
this.routeAfterLogin(false);
this.messageService.sendMessage('',Events.UserLogout);
break;
}
case 402: {
break;
}
case 200: {
//when success
break;
}
default: {
this.routeAfterLogin(false);
break;
}
}
},
error => {
console.log(error);
});
this.router.navigate(['/home']);
}
public login(data): Observable<any> {
return this.http.httpPost(ApiRoutes.LoginRoute,data).pipe(map(result=>{
if (result && result.status == 200) {
//when success
}else{
let msg = "some error message";
this.routeAfterLogin(false);
return {msg:msg};
}
}));
}
private routeAfterLogin(state:boolean) {
this.userIsLoggedIn = state;
if(this.userIsLoggedIn){
this.router.navigate(['/home']);
console.log("Login");
} else {
this.router.navigate(['/login']);
console.log("Failure Login");
}
}
public logout(): void {
let auth = this.http.httpGetAll(ApiRoutes.LogoutRoute);
auth.subscribe(
data => {
console.log("Logout");
this.messageService.sendMessage('',Events.UserLogout);
this.router.navigate(['/login']);
},
error => {
console.log(error);
});
}
public isAuthenticated(): boolean {
return this.userIsLoggedIn;
}
public fillFileDownloadPass(){
let getUploadPath$ = this.http.httpGetAll(ApiRoutes.DownloaPathdRout);
getUploadPath$.subscribe(
data => {
let results = data.json();
switch(results.status) {
case 200: {
this.session.download101AtchFilePath = results.filehDownloadPat;
this.session.approvedFormsPath = results.approvedFormsPath;
break;
}
case 400: {
console.log("didn't find an upload path");
break;
}
default: {
break;
}
}
},
error => {
console.log(error);
});
}
}
The handleAuthentication() function is called from the app.component..
ngOnInit() {
this.authService.handleAuthentication();
this.subscription = this.messageService.getMessage().subscribe(message => {
switch (message.type) {
case Events.UserLogin:
this.showNav = true;
break;
case Events.UserLogout:
this.showNav = false;
break;
case Events.FirstEntrance :
//some message
break;
}
});
}
The ApiService's httpPost function wraps the http:
httpPost(url:string,data:any):Observable<Response | any> {
return this._http.post(`${this.baseUrl}${url}`, data )
.map(this.parseData)
.catch(this.handleError.bind(this));
}
private parseData(res: Response) {
return res.json() || ;
}
There is a lot of abstraction in your code and is quite confusing. In the constructor, the http property is ApiService's instance and rHttp is the old Angular Http. I'm gonna edit my answer with any easy and straightforward way to do http calls using Angular's HttpClient and hope that helps you out.
– Anjil Dhamala
Nov 23 '18 at 3:18
I removed the ApiService and now using the http from '@angular/http' , for this post method ..didn't help..unfortunately.
– Victor Rodniansky
Nov 23 '18 at 6:37
Are you seeing any errors in your console? And don't use @angular/http. That has been replaced by HttpClient from '@angular/common/http'
– Anjil Dhamala
Nov 23 '18 at 20:14
No ,there is no any errors. About HttpClient , I know but thanks.
– Victor Rodniansky
Nov 23 '18 at 22:11
I don't see any code that would go out of angular's zone. If you initialize the message property in the constructor, are you able to see the message in the UI? There might be a disconnect between UI and the component class.
– Anjil Dhamala
Nov 24 '18 at 18:05
|
show 1 more comment
Try this and let me know.
- Make a property
loginRequest: Observable<any>;
- Inside
onSubmit()
:
onSubmit(request){
this.loginRequest = this.authService.login(request);
}
In your template,
<div>
{{ (loginRequest | async)?.msg }}
</div>
Here's a simple Http call.
import {HttpClient} from '@angular/common/http';
class SomeService {
constructor(private _http: HttpClient){}
postSomething() {
return this._http.post('url', toPost);
}
}
Thanks, unfortunately didn't help..
– Victor Rodniansky
Nov 22 '18 at 23:28
Where are you getting the httpPost() function from? That's not from Angular HttpClient. Your code might be going out of angular zone in that method.
– Anjil Dhamala
Nov 22 '18 at 23:29
Can you post your authService class along with the injections?
– Anjil Dhamala
Nov 22 '18 at 23:32
this post goes to NodeJs Api side..using ngZone.run .... didn't help too..
– Victor Rodniansky
Nov 22 '18 at 23:33
That doesn't help, Victor. I want to see your dependency Injections in AuthService class. Can you post your AuthService constructor?
– Anjil Dhamala
Nov 22 '18 at 23:35
|
show 1 more comment
I think it is a Zone related issue as you suggested..in that case:
onSubmit(request){
this.message="outer message"
this.loginRequest = this.authService.login(request);
this.loginRequest.subscribe((result) => {
if(result.msg){
this.message ="inner message"
// alert(this.message)
}
});
}
When onSubmit() fires , I see the "outer message" binding , but after entrance to subscription it disappears and the "inner message" is not shown at all.
add a comment |
I found the problem.
In my AuthService, in login() function, which returns an Observable, I am making a call for a this.routeAfterLogin(false) . This function redirects my route to login page in case the error occurs. That redirection inside an observable messes the change detection.
Actually I don't need it ,after removing it everything started to work fine.
Thanks all for the help.
public login(data): Observable<any> {
return this.rHttp.post(ApiRoutes.LoginRoute,data).pipe(map(result=>{
if(...){
// not relevant
}else{
let msg = "error message";
this.alertService.error(msg);
**this.routeAfterLogin(false);**
this.messageService.sendMessage('',Events.UserLogout);
return {msg:msg};
}
}));
}
**private routeAfterLogin(state:boolean)** {
this.userIsLoggedIn = state;
if(this.userIsLoggedIn){
this.router.navigate(['/home']);
console.log("Login");
} else {
this.router.navigate(['/login']);
console.log("Failure Login");
}
}
add a comment |
Your Answer
StackExchange.ifUsing("editor", function () {
StackExchange.using("externalEditor", function () {
StackExchange.using("snippets", function () {
StackExchange.snippets.init();
});
});
}, "code-snippets");
StackExchange.ready(function() {
var channelOptions = {
tags: "".split(" "),
id: "1"
};
initTagRenderer("".split(" "), "".split(" "), channelOptions);
StackExchange.using("externalEditor", function() {
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled) {
StackExchange.using("snippets", function() {
createEditor();
});
}
else {
createEditor();
}
});
function createEditor() {
StackExchange.prepareEditor({
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader: {
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
},
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
});
}
});
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53438210%2fhow-can-i-bind-from-a-callback-in-angular-4%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
6 Answers
6
active
oldest
votes
6 Answers
6
active
oldest
votes
active
oldest
votes
active
oldest
votes
I don't know exactly why this not happen.
But some question below.
Who is set msg
to the callback?
Maybe you want to do callbackFromLogin(result);
?
But I think you could try to implement another solution.
Why you are pass a callback to service and not do the function inside the subscription on the component?
Something like this:
// authorisation service
public login(data) {
return this.http.httpPost(ApiRoutes.LoginRoute, data);
// if you want manipulate the message you could use `pipe` method here
}
// and then in login component
onSubmit(request) {
this.authService.login().subscribe((message) => {
if(message){
this.message = message;
}
});
}
Sorry , for simplicity reasons , I removed some code from the snippet. The message is set after I am getting an error. let msg = "...."; callbackFromLogin(msg); the problem is that I have more logic in a service (in my subscription) I didn't want to move it to the login component, I wanted to send only the messag (msg)
– Victor Rodniansky
Nov 22 '18 at 22:06
You don't need to move the logic to the component, you could use RxJS operators likemap
,tap
, whatever you need and use them to apply your logic in the service. Then, in the subscribe only update the message in the component. I think this is the best practice.
– ptesser
Nov 22 '18 at 22:14
Thank you I changed my code..but still I am getting the same result ..the message is passed , but could not be changed in a binding ({{}}) I will post a new snippet now.
– Victor Rodniansky
Nov 22 '18 at 22:54
add a comment |
I don't know exactly why this not happen.
But some question below.
Who is set msg
to the callback?
Maybe you want to do callbackFromLogin(result);
?
But I think you could try to implement another solution.
Why you are pass a callback to service and not do the function inside the subscription on the component?
Something like this:
// authorisation service
public login(data) {
return this.http.httpPost(ApiRoutes.LoginRoute, data);
// if you want manipulate the message you could use `pipe` method here
}
// and then in login component
onSubmit(request) {
this.authService.login().subscribe((message) => {
if(message){
this.message = message;
}
});
}
Sorry , for simplicity reasons , I removed some code from the snippet. The message is set after I am getting an error. let msg = "...."; callbackFromLogin(msg); the problem is that I have more logic in a service (in my subscription) I didn't want to move it to the login component, I wanted to send only the messag (msg)
– Victor Rodniansky
Nov 22 '18 at 22:06
You don't need to move the logic to the component, you could use RxJS operators likemap
,tap
, whatever you need and use them to apply your logic in the service. Then, in the subscribe only update the message in the component. I think this is the best practice.
– ptesser
Nov 22 '18 at 22:14
Thank you I changed my code..but still I am getting the same result ..the message is passed , but could not be changed in a binding ({{}}) I will post a new snippet now.
– Victor Rodniansky
Nov 22 '18 at 22:54
add a comment |
I don't know exactly why this not happen.
But some question below.
Who is set msg
to the callback?
Maybe you want to do callbackFromLogin(result);
?
But I think you could try to implement another solution.
Why you are pass a callback to service and not do the function inside the subscription on the component?
Something like this:
// authorisation service
public login(data) {
return this.http.httpPost(ApiRoutes.LoginRoute, data);
// if you want manipulate the message you could use `pipe` method here
}
// and then in login component
onSubmit(request) {
this.authService.login().subscribe((message) => {
if(message){
this.message = message;
}
});
}
I don't know exactly why this not happen.
But some question below.
Who is set msg
to the callback?
Maybe you want to do callbackFromLogin(result);
?
But I think you could try to implement another solution.
Why you are pass a callback to service and not do the function inside the subscription on the component?
Something like this:
// authorisation service
public login(data) {
return this.http.httpPost(ApiRoutes.LoginRoute, data);
// if you want manipulate the message you could use `pipe` method here
}
// and then in login component
onSubmit(request) {
this.authService.login().subscribe((message) => {
if(message){
this.message = message;
}
});
}
answered Nov 22 '18 at 21:56
ptesserptesser
224410
224410
Sorry , for simplicity reasons , I removed some code from the snippet. The message is set after I am getting an error. let msg = "...."; callbackFromLogin(msg); the problem is that I have more logic in a service (in my subscription) I didn't want to move it to the login component, I wanted to send only the messag (msg)
– Victor Rodniansky
Nov 22 '18 at 22:06
You don't need to move the logic to the component, you could use RxJS operators likemap
,tap
, whatever you need and use them to apply your logic in the service. Then, in the subscribe only update the message in the component. I think this is the best practice.
– ptesser
Nov 22 '18 at 22:14
Thank you I changed my code..but still I am getting the same result ..the message is passed , but could not be changed in a binding ({{}}) I will post a new snippet now.
– Victor Rodniansky
Nov 22 '18 at 22:54
add a comment |
Sorry , for simplicity reasons , I removed some code from the snippet. The message is set after I am getting an error. let msg = "...."; callbackFromLogin(msg); the problem is that I have more logic in a service (in my subscription) I didn't want to move it to the login component, I wanted to send only the messag (msg)
– Victor Rodniansky
Nov 22 '18 at 22:06
You don't need to move the logic to the component, you could use RxJS operators likemap
,tap
, whatever you need and use them to apply your logic in the service. Then, in the subscribe only update the message in the component. I think this is the best practice.
– ptesser
Nov 22 '18 at 22:14
Thank you I changed my code..but still I am getting the same result ..the message is passed , but could not be changed in a binding ({{}}) I will post a new snippet now.
– Victor Rodniansky
Nov 22 '18 at 22:54
Sorry , for simplicity reasons , I removed some code from the snippet. The message is set after I am getting an error. let msg = "...."; callbackFromLogin(msg); the problem is that I have more logic in a service (in my subscription) I didn't want to move it to the login component, I wanted to send only the messag (msg)
– Victor Rodniansky
Nov 22 '18 at 22:06
Sorry , for simplicity reasons , I removed some code from the snippet. The message is set after I am getting an error. let msg = "...."; callbackFromLogin(msg); the problem is that I have more logic in a service (in my subscription) I didn't want to move it to the login component, I wanted to send only the messag (msg)
– Victor Rodniansky
Nov 22 '18 at 22:06
You don't need to move the logic to the component, you could use RxJS operators like
map
, tap
, whatever you need and use them to apply your logic in the service. Then, in the subscribe only update the message in the component. I think this is the best practice.– ptesser
Nov 22 '18 at 22:14
You don't need to move the logic to the component, you could use RxJS operators like
map
, tap
, whatever you need and use them to apply your logic in the service. Then, in the subscribe only update the message in the component. I think this is the best practice.– ptesser
Nov 22 '18 at 22:14
Thank you I changed my code..but still I am getting the same result ..the message is passed , but could not be changed in a binding ({{}}) I will post a new snippet now.
– Victor Rodniansky
Nov 22 '18 at 22:54
Thank you I changed my code..but still I am getting the same result ..the message is passed , but could not be changed in a binding ({{}}) I will post a new snippet now.
– Victor Rodniansky
Nov 22 '18 at 22:54
add a comment |
I used your advise and change my code to this:
//Service
public login(data): Observable<any> {
return this.http.httpPost(ApiRoutes.LoginRoute,data).pipe(map(result=>{
if (result && result.status == 200) {
///
}else{
let msg = `my message`;
return {msg:msg};
}
}));
}
//login component
onSubmit(request){
this.authService.login(request).subscribe((result) => {
if(result.msg){
this.message = result.msg;
alert( this.message )
}
});
}
<div>{{message}}</div>
Same issue , the message is passed to result ,when I call to alert( this.message ) function , the message is shown above..but there is no change in a template Interpolation however.
I suppose it could be some issue in my app..because I know such code should trigger the change... What could be a reason for this strange behavior.
– Victor Rodniansky
Nov 22 '18 at 23:11
Where are you getting the httpPost() method from? Angular's HttpClient doesn't have a httpPost() method.
– Anjil Dhamala
Nov 22 '18 at 23:17
add a comment |
I used your advise and change my code to this:
//Service
public login(data): Observable<any> {
return this.http.httpPost(ApiRoutes.LoginRoute,data).pipe(map(result=>{
if (result && result.status == 200) {
///
}else{
let msg = `my message`;
return {msg:msg};
}
}));
}
//login component
onSubmit(request){
this.authService.login(request).subscribe((result) => {
if(result.msg){
this.message = result.msg;
alert( this.message )
}
});
}
<div>{{message}}</div>
Same issue , the message is passed to result ,when I call to alert( this.message ) function , the message is shown above..but there is no change in a template Interpolation however.
I suppose it could be some issue in my app..because I know such code should trigger the change... What could be a reason for this strange behavior.
– Victor Rodniansky
Nov 22 '18 at 23:11
Where are you getting the httpPost() method from? Angular's HttpClient doesn't have a httpPost() method.
– Anjil Dhamala
Nov 22 '18 at 23:17
add a comment |
I used your advise and change my code to this:
//Service
public login(data): Observable<any> {
return this.http.httpPost(ApiRoutes.LoginRoute,data).pipe(map(result=>{
if (result && result.status == 200) {
///
}else{
let msg = `my message`;
return {msg:msg};
}
}));
}
//login component
onSubmit(request){
this.authService.login(request).subscribe((result) => {
if(result.msg){
this.message = result.msg;
alert( this.message )
}
});
}
<div>{{message}}</div>
Same issue , the message is passed to result ,when I call to alert( this.message ) function , the message is shown above..but there is no change in a template Interpolation however.
I used your advise and change my code to this:
//Service
public login(data): Observable<any> {
return this.http.httpPost(ApiRoutes.LoginRoute,data).pipe(map(result=>{
if (result && result.status == 200) {
///
}else{
let msg = `my message`;
return {msg:msg};
}
}));
}
//login component
onSubmit(request){
this.authService.login(request).subscribe((result) => {
if(result.msg){
this.message = result.msg;
alert( this.message )
}
});
}
<div>{{message}}</div>
Same issue , the message is passed to result ,when I call to alert( this.message ) function , the message is shown above..but there is no change in a template Interpolation however.
//Service
public login(data): Observable<any> {
return this.http.httpPost(ApiRoutes.LoginRoute,data).pipe(map(result=>{
if (result && result.status == 200) {
///
}else{
let msg = `my message`;
return {msg:msg};
}
}));
}
//login component
onSubmit(request){
this.authService.login(request).subscribe((result) => {
if(result.msg){
this.message = result.msg;
alert( this.message )
}
});
}
<div>{{message}}</div>
//Service
public login(data): Observable<any> {
return this.http.httpPost(ApiRoutes.LoginRoute,data).pipe(map(result=>{
if (result && result.status == 200) {
///
}else{
let msg = `my message`;
return {msg:msg};
}
}));
}
//login component
onSubmit(request){
this.authService.login(request).subscribe((result) => {
if(result.msg){
this.message = result.msg;
alert( this.message )
}
});
}
<div>{{message}}</div>
answered Nov 22 '18 at 23:05
Victor RodnianskyVictor Rodniansky
5018
5018
I suppose it could be some issue in my app..because I know such code should trigger the change... What could be a reason for this strange behavior.
– Victor Rodniansky
Nov 22 '18 at 23:11
Where are you getting the httpPost() method from? Angular's HttpClient doesn't have a httpPost() method.
– Anjil Dhamala
Nov 22 '18 at 23:17
add a comment |
I suppose it could be some issue in my app..because I know such code should trigger the change... What could be a reason for this strange behavior.
– Victor Rodniansky
Nov 22 '18 at 23:11
Where are you getting the httpPost() method from? Angular's HttpClient doesn't have a httpPost() method.
– Anjil Dhamala
Nov 22 '18 at 23:17
I suppose it could be some issue in my app..because I know such code should trigger the change... What could be a reason for this strange behavior.
– Victor Rodniansky
Nov 22 '18 at 23:11
I suppose it could be some issue in my app..because I know such code should trigger the change... What could be a reason for this strange behavior.
– Victor Rodniansky
Nov 22 '18 at 23:11
Where are you getting the httpPost() method from? Angular's HttpClient doesn't have a httpPost() method.
– Anjil Dhamala
Nov 22 '18 at 23:17
Where are you getting the httpPost() method from? Angular's HttpClient doesn't have a httpPost() method.
– Anjil Dhamala
Nov 22 '18 at 23:17
add a comment |
Yes..here is an AuthService:
import { SessionService } from '../session/session.service';
import { environment } from './../../../environments/environment';
import { IUser, UserType } from '../../../../../contracts/IUser';
import { IEmployee } from '../../../../../contracts/IEmployee';
import { Injectable,Inject } from '@angular/core';
import { Router } from '@angular/router';
import 'rxjs/add/operator/filter';
import * as auth0 from 'auth0-js';
import { Http } from '@angular/http';
import {ReplaySubject, Observable} from 'rxjs/Rx';
import { ApiService } from '../api/api.service';
import { ActivityService } from '../activity/activity.service';
import { UserActivityAction } from '../../../../../contracts/Library';
import { ApiRoutes } from '../../../../../contracts/ApiRoutes';
import { AlertService} from '../alert/alert.service';
import { MessageService} from '../message/message.service';
import {Events} from '../../../../../contracts/Library';
import { map } from 'rxjs/operators';
@Injectable()
export class AuthService {
private userIsLoggedIn : boolean;
constructor(public http: ApiService,private rHttp: Http,
private session:SessionService,
@Inject('BASE_URL') public baseUrl: string,
public router: Router,
private alertService: AlertService,
private activity: ActivityService,
private messageService : MessageService)
{
this.session = session;
}
// logIn attempts to log in a user
handleAuthentication() : void {
let auth = this.http.httpGetAll(ApiRoutes.AuthRoute);
auth.subscribe(
data => {
let results = data.json();
switch(results.status) {
case 401: {
this.routeAfterLogin(false);
this.messageService.sendMessage('',Events.UserLogout);
break;
}
case 402: {
break;
}
case 200: {
//when success
break;
}
default: {
this.routeAfterLogin(false);
break;
}
}
},
error => {
console.log(error);
});
this.router.navigate(['/home']);
}
public login(data): Observable<any> {
return this.http.httpPost(ApiRoutes.LoginRoute,data).pipe(map(result=>{
if (result && result.status == 200) {
//when success
}else{
let msg = "some error message";
this.routeAfterLogin(false);
return {msg:msg};
}
}));
}
private routeAfterLogin(state:boolean) {
this.userIsLoggedIn = state;
if(this.userIsLoggedIn){
this.router.navigate(['/home']);
console.log("Login");
} else {
this.router.navigate(['/login']);
console.log("Failure Login");
}
}
public logout(): void {
let auth = this.http.httpGetAll(ApiRoutes.LogoutRoute);
auth.subscribe(
data => {
console.log("Logout");
this.messageService.sendMessage('',Events.UserLogout);
this.router.navigate(['/login']);
},
error => {
console.log(error);
});
}
public isAuthenticated(): boolean {
return this.userIsLoggedIn;
}
public fillFileDownloadPass(){
let getUploadPath$ = this.http.httpGetAll(ApiRoutes.DownloaPathdRout);
getUploadPath$.subscribe(
data => {
let results = data.json();
switch(results.status) {
case 200: {
this.session.download101AtchFilePath = results.filehDownloadPat;
this.session.approvedFormsPath = results.approvedFormsPath;
break;
}
case 400: {
console.log("didn't find an upload path");
break;
}
default: {
break;
}
}
},
error => {
console.log(error);
});
}
}
The handleAuthentication() function is called from the app.component..
ngOnInit() {
this.authService.handleAuthentication();
this.subscription = this.messageService.getMessage().subscribe(message => {
switch (message.type) {
case Events.UserLogin:
this.showNav = true;
break;
case Events.UserLogout:
this.showNav = false;
break;
case Events.FirstEntrance :
//some message
break;
}
});
}
The ApiService's httpPost function wraps the http:
httpPost(url:string,data:any):Observable<Response | any> {
return this._http.post(`${this.baseUrl}${url}`, data )
.map(this.parseData)
.catch(this.handleError.bind(this));
}
private parseData(res: Response) {
return res.json() || ;
}
There is a lot of abstraction in your code and is quite confusing. In the constructor, the http property is ApiService's instance and rHttp is the old Angular Http. I'm gonna edit my answer with any easy and straightforward way to do http calls using Angular's HttpClient and hope that helps you out.
– Anjil Dhamala
Nov 23 '18 at 3:18
I removed the ApiService and now using the http from '@angular/http' , for this post method ..didn't help..unfortunately.
– Victor Rodniansky
Nov 23 '18 at 6:37
Are you seeing any errors in your console? And don't use @angular/http. That has been replaced by HttpClient from '@angular/common/http'
– Anjil Dhamala
Nov 23 '18 at 20:14
No ,there is no any errors. About HttpClient , I know but thanks.
– Victor Rodniansky
Nov 23 '18 at 22:11
I don't see any code that would go out of angular's zone. If you initialize the message property in the constructor, are you able to see the message in the UI? There might be a disconnect between UI and the component class.
– Anjil Dhamala
Nov 24 '18 at 18:05
|
show 1 more comment
Yes..here is an AuthService:
import { SessionService } from '../session/session.service';
import { environment } from './../../../environments/environment';
import { IUser, UserType } from '../../../../../contracts/IUser';
import { IEmployee } from '../../../../../contracts/IEmployee';
import { Injectable,Inject } from '@angular/core';
import { Router } from '@angular/router';
import 'rxjs/add/operator/filter';
import * as auth0 from 'auth0-js';
import { Http } from '@angular/http';
import {ReplaySubject, Observable} from 'rxjs/Rx';
import { ApiService } from '../api/api.service';
import { ActivityService } from '../activity/activity.service';
import { UserActivityAction } from '../../../../../contracts/Library';
import { ApiRoutes } from '../../../../../contracts/ApiRoutes';
import { AlertService} from '../alert/alert.service';
import { MessageService} from '../message/message.service';
import {Events} from '../../../../../contracts/Library';
import { map } from 'rxjs/operators';
@Injectable()
export class AuthService {
private userIsLoggedIn : boolean;
constructor(public http: ApiService,private rHttp: Http,
private session:SessionService,
@Inject('BASE_URL') public baseUrl: string,
public router: Router,
private alertService: AlertService,
private activity: ActivityService,
private messageService : MessageService)
{
this.session = session;
}
// logIn attempts to log in a user
handleAuthentication() : void {
let auth = this.http.httpGetAll(ApiRoutes.AuthRoute);
auth.subscribe(
data => {
let results = data.json();
switch(results.status) {
case 401: {
this.routeAfterLogin(false);
this.messageService.sendMessage('',Events.UserLogout);
break;
}
case 402: {
break;
}
case 200: {
//when success
break;
}
default: {
this.routeAfterLogin(false);
break;
}
}
},
error => {
console.log(error);
});
this.router.navigate(['/home']);
}
public login(data): Observable<any> {
return this.http.httpPost(ApiRoutes.LoginRoute,data).pipe(map(result=>{
if (result && result.status == 200) {
//when success
}else{
let msg = "some error message";
this.routeAfterLogin(false);
return {msg:msg};
}
}));
}
private routeAfterLogin(state:boolean) {
this.userIsLoggedIn = state;
if(this.userIsLoggedIn){
this.router.navigate(['/home']);
console.log("Login");
} else {
this.router.navigate(['/login']);
console.log("Failure Login");
}
}
public logout(): void {
let auth = this.http.httpGetAll(ApiRoutes.LogoutRoute);
auth.subscribe(
data => {
console.log("Logout");
this.messageService.sendMessage('',Events.UserLogout);
this.router.navigate(['/login']);
},
error => {
console.log(error);
});
}
public isAuthenticated(): boolean {
return this.userIsLoggedIn;
}
public fillFileDownloadPass(){
let getUploadPath$ = this.http.httpGetAll(ApiRoutes.DownloaPathdRout);
getUploadPath$.subscribe(
data => {
let results = data.json();
switch(results.status) {
case 200: {
this.session.download101AtchFilePath = results.filehDownloadPat;
this.session.approvedFormsPath = results.approvedFormsPath;
break;
}
case 400: {
console.log("didn't find an upload path");
break;
}
default: {
break;
}
}
},
error => {
console.log(error);
});
}
}
The handleAuthentication() function is called from the app.component..
ngOnInit() {
this.authService.handleAuthentication();
this.subscription = this.messageService.getMessage().subscribe(message => {
switch (message.type) {
case Events.UserLogin:
this.showNav = true;
break;
case Events.UserLogout:
this.showNav = false;
break;
case Events.FirstEntrance :
//some message
break;
}
});
}
The ApiService's httpPost function wraps the http:
httpPost(url:string,data:any):Observable<Response | any> {
return this._http.post(`${this.baseUrl}${url}`, data )
.map(this.parseData)
.catch(this.handleError.bind(this));
}
private parseData(res: Response) {
return res.json() || ;
}
There is a lot of abstraction in your code and is quite confusing. In the constructor, the http property is ApiService's instance and rHttp is the old Angular Http. I'm gonna edit my answer with any easy and straightforward way to do http calls using Angular's HttpClient and hope that helps you out.
– Anjil Dhamala
Nov 23 '18 at 3:18
I removed the ApiService and now using the http from '@angular/http' , for this post method ..didn't help..unfortunately.
– Victor Rodniansky
Nov 23 '18 at 6:37
Are you seeing any errors in your console? And don't use @angular/http. That has been replaced by HttpClient from '@angular/common/http'
– Anjil Dhamala
Nov 23 '18 at 20:14
No ,there is no any errors. About HttpClient , I know but thanks.
– Victor Rodniansky
Nov 23 '18 at 22:11
I don't see any code that would go out of angular's zone. If you initialize the message property in the constructor, are you able to see the message in the UI? There might be a disconnect between UI and the component class.
– Anjil Dhamala
Nov 24 '18 at 18:05
|
show 1 more comment
Yes..here is an AuthService:
import { SessionService } from '../session/session.service';
import { environment } from './../../../environments/environment';
import { IUser, UserType } from '../../../../../contracts/IUser';
import { IEmployee } from '../../../../../contracts/IEmployee';
import { Injectable,Inject } from '@angular/core';
import { Router } from '@angular/router';
import 'rxjs/add/operator/filter';
import * as auth0 from 'auth0-js';
import { Http } from '@angular/http';
import {ReplaySubject, Observable} from 'rxjs/Rx';
import { ApiService } from '../api/api.service';
import { ActivityService } from '../activity/activity.service';
import { UserActivityAction } from '../../../../../contracts/Library';
import { ApiRoutes } from '../../../../../contracts/ApiRoutes';
import { AlertService} from '../alert/alert.service';
import { MessageService} from '../message/message.service';
import {Events} from '../../../../../contracts/Library';
import { map } from 'rxjs/operators';
@Injectable()
export class AuthService {
private userIsLoggedIn : boolean;
constructor(public http: ApiService,private rHttp: Http,
private session:SessionService,
@Inject('BASE_URL') public baseUrl: string,
public router: Router,
private alertService: AlertService,
private activity: ActivityService,
private messageService : MessageService)
{
this.session = session;
}
// logIn attempts to log in a user
handleAuthentication() : void {
let auth = this.http.httpGetAll(ApiRoutes.AuthRoute);
auth.subscribe(
data => {
let results = data.json();
switch(results.status) {
case 401: {
this.routeAfterLogin(false);
this.messageService.sendMessage('',Events.UserLogout);
break;
}
case 402: {
break;
}
case 200: {
//when success
break;
}
default: {
this.routeAfterLogin(false);
break;
}
}
},
error => {
console.log(error);
});
this.router.navigate(['/home']);
}
public login(data): Observable<any> {
return this.http.httpPost(ApiRoutes.LoginRoute,data).pipe(map(result=>{
if (result && result.status == 200) {
//when success
}else{
let msg = "some error message";
this.routeAfterLogin(false);
return {msg:msg};
}
}));
}
private routeAfterLogin(state:boolean) {
this.userIsLoggedIn = state;
if(this.userIsLoggedIn){
this.router.navigate(['/home']);
console.log("Login");
} else {
this.router.navigate(['/login']);
console.log("Failure Login");
}
}
public logout(): void {
let auth = this.http.httpGetAll(ApiRoutes.LogoutRoute);
auth.subscribe(
data => {
console.log("Logout");
this.messageService.sendMessage('',Events.UserLogout);
this.router.navigate(['/login']);
},
error => {
console.log(error);
});
}
public isAuthenticated(): boolean {
return this.userIsLoggedIn;
}
public fillFileDownloadPass(){
let getUploadPath$ = this.http.httpGetAll(ApiRoutes.DownloaPathdRout);
getUploadPath$.subscribe(
data => {
let results = data.json();
switch(results.status) {
case 200: {
this.session.download101AtchFilePath = results.filehDownloadPat;
this.session.approvedFormsPath = results.approvedFormsPath;
break;
}
case 400: {
console.log("didn't find an upload path");
break;
}
default: {
break;
}
}
},
error => {
console.log(error);
});
}
}
The handleAuthentication() function is called from the app.component..
ngOnInit() {
this.authService.handleAuthentication();
this.subscription = this.messageService.getMessage().subscribe(message => {
switch (message.type) {
case Events.UserLogin:
this.showNav = true;
break;
case Events.UserLogout:
this.showNav = false;
break;
case Events.FirstEntrance :
//some message
break;
}
});
}
The ApiService's httpPost function wraps the http:
httpPost(url:string,data:any):Observable<Response | any> {
return this._http.post(`${this.baseUrl}${url}`, data )
.map(this.parseData)
.catch(this.handleError.bind(this));
}
private parseData(res: Response) {
return res.json() || ;
}
Yes..here is an AuthService:
import { SessionService } from '../session/session.service';
import { environment } from './../../../environments/environment';
import { IUser, UserType } from '../../../../../contracts/IUser';
import { IEmployee } from '../../../../../contracts/IEmployee';
import { Injectable,Inject } from '@angular/core';
import { Router } from '@angular/router';
import 'rxjs/add/operator/filter';
import * as auth0 from 'auth0-js';
import { Http } from '@angular/http';
import {ReplaySubject, Observable} from 'rxjs/Rx';
import { ApiService } from '../api/api.service';
import { ActivityService } from '../activity/activity.service';
import { UserActivityAction } from '../../../../../contracts/Library';
import { ApiRoutes } from '../../../../../contracts/ApiRoutes';
import { AlertService} from '../alert/alert.service';
import { MessageService} from '../message/message.service';
import {Events} from '../../../../../contracts/Library';
import { map } from 'rxjs/operators';
@Injectable()
export class AuthService {
private userIsLoggedIn : boolean;
constructor(public http: ApiService,private rHttp: Http,
private session:SessionService,
@Inject('BASE_URL') public baseUrl: string,
public router: Router,
private alertService: AlertService,
private activity: ActivityService,
private messageService : MessageService)
{
this.session = session;
}
// logIn attempts to log in a user
handleAuthentication() : void {
let auth = this.http.httpGetAll(ApiRoutes.AuthRoute);
auth.subscribe(
data => {
let results = data.json();
switch(results.status) {
case 401: {
this.routeAfterLogin(false);
this.messageService.sendMessage('',Events.UserLogout);
break;
}
case 402: {
break;
}
case 200: {
//when success
break;
}
default: {
this.routeAfterLogin(false);
break;
}
}
},
error => {
console.log(error);
});
this.router.navigate(['/home']);
}
public login(data): Observable<any> {
return this.http.httpPost(ApiRoutes.LoginRoute,data).pipe(map(result=>{
if (result && result.status == 200) {
//when success
}else{
let msg = "some error message";
this.routeAfterLogin(false);
return {msg:msg};
}
}));
}
private routeAfterLogin(state:boolean) {
this.userIsLoggedIn = state;
if(this.userIsLoggedIn){
this.router.navigate(['/home']);
console.log("Login");
} else {
this.router.navigate(['/login']);
console.log("Failure Login");
}
}
public logout(): void {
let auth = this.http.httpGetAll(ApiRoutes.LogoutRoute);
auth.subscribe(
data => {
console.log("Logout");
this.messageService.sendMessage('',Events.UserLogout);
this.router.navigate(['/login']);
},
error => {
console.log(error);
});
}
public isAuthenticated(): boolean {
return this.userIsLoggedIn;
}
public fillFileDownloadPass(){
let getUploadPath$ = this.http.httpGetAll(ApiRoutes.DownloaPathdRout);
getUploadPath$.subscribe(
data => {
let results = data.json();
switch(results.status) {
case 200: {
this.session.download101AtchFilePath = results.filehDownloadPat;
this.session.approvedFormsPath = results.approvedFormsPath;
break;
}
case 400: {
console.log("didn't find an upload path");
break;
}
default: {
break;
}
}
},
error => {
console.log(error);
});
}
}
The handleAuthentication() function is called from the app.component..
ngOnInit() {
this.authService.handleAuthentication();
this.subscription = this.messageService.getMessage().subscribe(message => {
switch (message.type) {
case Events.UserLogin:
this.showNav = true;
break;
case Events.UserLogout:
this.showNav = false;
break;
case Events.FirstEntrance :
//some message
break;
}
});
}
The ApiService's httpPost function wraps the http:
httpPost(url:string,data:any):Observable<Response | any> {
return this._http.post(`${this.baseUrl}${url}`, data )
.map(this.parseData)
.catch(this.handleError.bind(this));
}
private parseData(res: Response) {
return res.json() || ;
}
import { SessionService } from '../session/session.service';
import { environment } from './../../../environments/environment';
import { IUser, UserType } from '../../../../../contracts/IUser';
import { IEmployee } from '../../../../../contracts/IEmployee';
import { Injectable,Inject } from '@angular/core';
import { Router } from '@angular/router';
import 'rxjs/add/operator/filter';
import * as auth0 from 'auth0-js';
import { Http } from '@angular/http';
import {ReplaySubject, Observable} from 'rxjs/Rx';
import { ApiService } from '../api/api.service';
import { ActivityService } from '../activity/activity.service';
import { UserActivityAction } from '../../../../../contracts/Library';
import { ApiRoutes } from '../../../../../contracts/ApiRoutes';
import { AlertService} from '../alert/alert.service';
import { MessageService} from '../message/message.service';
import {Events} from '../../../../../contracts/Library';
import { map } from 'rxjs/operators';
@Injectable()
export class AuthService {
private userIsLoggedIn : boolean;
constructor(public http: ApiService,private rHttp: Http,
private session:SessionService,
@Inject('BASE_URL') public baseUrl: string,
public router: Router,
private alertService: AlertService,
private activity: ActivityService,
private messageService : MessageService)
{
this.session = session;
}
// logIn attempts to log in a user
handleAuthentication() : void {
let auth = this.http.httpGetAll(ApiRoutes.AuthRoute);
auth.subscribe(
data => {
let results = data.json();
switch(results.status) {
case 401: {
this.routeAfterLogin(false);
this.messageService.sendMessage('',Events.UserLogout);
break;
}
case 402: {
break;
}
case 200: {
//when success
break;
}
default: {
this.routeAfterLogin(false);
break;
}
}
},
error => {
console.log(error);
});
this.router.navigate(['/home']);
}
public login(data): Observable<any> {
return this.http.httpPost(ApiRoutes.LoginRoute,data).pipe(map(result=>{
if (result && result.status == 200) {
//when success
}else{
let msg = "some error message";
this.routeAfterLogin(false);
return {msg:msg};
}
}));
}
private routeAfterLogin(state:boolean) {
this.userIsLoggedIn = state;
if(this.userIsLoggedIn){
this.router.navigate(['/home']);
console.log("Login");
} else {
this.router.navigate(['/login']);
console.log("Failure Login");
}
}
public logout(): void {
let auth = this.http.httpGetAll(ApiRoutes.LogoutRoute);
auth.subscribe(
data => {
console.log("Logout");
this.messageService.sendMessage('',Events.UserLogout);
this.router.navigate(['/login']);
},
error => {
console.log(error);
});
}
public isAuthenticated(): boolean {
return this.userIsLoggedIn;
}
public fillFileDownloadPass(){
let getUploadPath$ = this.http.httpGetAll(ApiRoutes.DownloaPathdRout);
getUploadPath$.subscribe(
data => {
let results = data.json();
switch(results.status) {
case 200: {
this.session.download101AtchFilePath = results.filehDownloadPat;
this.session.approvedFormsPath = results.approvedFormsPath;
break;
}
case 400: {
console.log("didn't find an upload path");
break;
}
default: {
break;
}
}
},
error => {
console.log(error);
});
}
}
import { SessionService } from '../session/session.service';
import { environment } from './../../../environments/environment';
import { IUser, UserType } from '../../../../../contracts/IUser';
import { IEmployee } from '../../../../../contracts/IEmployee';
import { Injectable,Inject } from '@angular/core';
import { Router } from '@angular/router';
import 'rxjs/add/operator/filter';
import * as auth0 from 'auth0-js';
import { Http } from '@angular/http';
import {ReplaySubject, Observable} from 'rxjs/Rx';
import { ApiService } from '../api/api.service';
import { ActivityService } from '../activity/activity.service';
import { UserActivityAction } from '../../../../../contracts/Library';
import { ApiRoutes } from '../../../../../contracts/ApiRoutes';
import { AlertService} from '../alert/alert.service';
import { MessageService} from '../message/message.service';
import {Events} from '../../../../../contracts/Library';
import { map } from 'rxjs/operators';
@Injectable()
export class AuthService {
private userIsLoggedIn : boolean;
constructor(public http: ApiService,private rHttp: Http,
private session:SessionService,
@Inject('BASE_URL') public baseUrl: string,
public router: Router,
private alertService: AlertService,
private activity: ActivityService,
private messageService : MessageService)
{
this.session = session;
}
// logIn attempts to log in a user
handleAuthentication() : void {
let auth = this.http.httpGetAll(ApiRoutes.AuthRoute);
auth.subscribe(
data => {
let results = data.json();
switch(results.status) {
case 401: {
this.routeAfterLogin(false);
this.messageService.sendMessage('',Events.UserLogout);
break;
}
case 402: {
break;
}
case 200: {
//when success
break;
}
default: {
this.routeAfterLogin(false);
break;
}
}
},
error => {
console.log(error);
});
this.router.navigate(['/home']);
}
public login(data): Observable<any> {
return this.http.httpPost(ApiRoutes.LoginRoute,data).pipe(map(result=>{
if (result && result.status == 200) {
//when success
}else{
let msg = "some error message";
this.routeAfterLogin(false);
return {msg:msg};
}
}));
}
private routeAfterLogin(state:boolean) {
this.userIsLoggedIn = state;
if(this.userIsLoggedIn){
this.router.navigate(['/home']);
console.log("Login");
} else {
this.router.navigate(['/login']);
console.log("Failure Login");
}
}
public logout(): void {
let auth = this.http.httpGetAll(ApiRoutes.LogoutRoute);
auth.subscribe(
data => {
console.log("Logout");
this.messageService.sendMessage('',Events.UserLogout);
this.router.navigate(['/login']);
},
error => {
console.log(error);
});
}
public isAuthenticated(): boolean {
return this.userIsLoggedIn;
}
public fillFileDownloadPass(){
let getUploadPath$ = this.http.httpGetAll(ApiRoutes.DownloaPathdRout);
getUploadPath$.subscribe(
data => {
let results = data.json();
switch(results.status) {
case 200: {
this.session.download101AtchFilePath = results.filehDownloadPat;
this.session.approvedFormsPath = results.approvedFormsPath;
break;
}
case 400: {
console.log("didn't find an upload path");
break;
}
default: {
break;
}
}
},
error => {
console.log(error);
});
}
}
ngOnInit() {
this.authService.handleAuthentication();
this.subscription = this.messageService.getMessage().subscribe(message => {
switch (message.type) {
case Events.UserLogin:
this.showNav = true;
break;
case Events.UserLogout:
this.showNav = false;
break;
case Events.FirstEntrance :
//some message
break;
}
});
}
ngOnInit() {
this.authService.handleAuthentication();
this.subscription = this.messageService.getMessage().subscribe(message => {
switch (message.type) {
case Events.UserLogin:
this.showNav = true;
break;
case Events.UserLogout:
this.showNav = false;
break;
case Events.FirstEntrance :
//some message
break;
}
});
}
httpPost(url:string,data:any):Observable<Response | any> {
return this._http.post(`${this.baseUrl}${url}`, data )
.map(this.parseData)
.catch(this.handleError.bind(this));
}
private parseData(res: Response) {
return res.json() || ;
}
httpPost(url:string,data:any):Observable<Response | any> {
return this._http.post(`${this.baseUrl}${url}`, data )
.map(this.parseData)
.catch(this.handleError.bind(this));
}
private parseData(res: Response) {
return res.json() || ;
}
edited Nov 23 '18 at 0:09
answered Nov 22 '18 at 23:54
Victor RodnianskyVictor Rodniansky
5018
5018
There is a lot of abstraction in your code and is quite confusing. In the constructor, the http property is ApiService's instance and rHttp is the old Angular Http. I'm gonna edit my answer with any easy and straightforward way to do http calls using Angular's HttpClient and hope that helps you out.
– Anjil Dhamala
Nov 23 '18 at 3:18
I removed the ApiService and now using the http from '@angular/http' , for this post method ..didn't help..unfortunately.
– Victor Rodniansky
Nov 23 '18 at 6:37
Are you seeing any errors in your console? And don't use @angular/http. That has been replaced by HttpClient from '@angular/common/http'
– Anjil Dhamala
Nov 23 '18 at 20:14
No ,there is no any errors. About HttpClient , I know but thanks.
– Victor Rodniansky
Nov 23 '18 at 22:11
I don't see any code that would go out of angular's zone. If you initialize the message property in the constructor, are you able to see the message in the UI? There might be a disconnect between UI and the component class.
– Anjil Dhamala
Nov 24 '18 at 18:05
|
show 1 more comment
There is a lot of abstraction in your code and is quite confusing. In the constructor, the http property is ApiService's instance and rHttp is the old Angular Http. I'm gonna edit my answer with any easy and straightforward way to do http calls using Angular's HttpClient and hope that helps you out.
– Anjil Dhamala
Nov 23 '18 at 3:18
I removed the ApiService and now using the http from '@angular/http' , for this post method ..didn't help..unfortunately.
– Victor Rodniansky
Nov 23 '18 at 6:37
Are you seeing any errors in your console? And don't use @angular/http. That has been replaced by HttpClient from '@angular/common/http'
– Anjil Dhamala
Nov 23 '18 at 20:14
No ,there is no any errors. About HttpClient , I know but thanks.
– Victor Rodniansky
Nov 23 '18 at 22:11
I don't see any code that would go out of angular's zone. If you initialize the message property in the constructor, are you able to see the message in the UI? There might be a disconnect between UI and the component class.
– Anjil Dhamala
Nov 24 '18 at 18:05
There is a lot of abstraction in your code and is quite confusing. In the constructor, the http property is ApiService's instance and rHttp is the old Angular Http. I'm gonna edit my answer with any easy and straightforward way to do http calls using Angular's HttpClient and hope that helps you out.
– Anjil Dhamala
Nov 23 '18 at 3:18
There is a lot of abstraction in your code and is quite confusing. In the constructor, the http property is ApiService's instance and rHttp is the old Angular Http. I'm gonna edit my answer with any easy and straightforward way to do http calls using Angular's HttpClient and hope that helps you out.
– Anjil Dhamala
Nov 23 '18 at 3:18
I removed the ApiService and now using the http from '@angular/http' , for this post method ..didn't help..unfortunately.
– Victor Rodniansky
Nov 23 '18 at 6:37
I removed the ApiService and now using the http from '@angular/http' , for this post method ..didn't help..unfortunately.
– Victor Rodniansky
Nov 23 '18 at 6:37
Are you seeing any errors in your console? And don't use @angular/http. That has been replaced by HttpClient from '@angular/common/http'
– Anjil Dhamala
Nov 23 '18 at 20:14
Are you seeing any errors in your console? And don't use @angular/http. That has been replaced by HttpClient from '@angular/common/http'
– Anjil Dhamala
Nov 23 '18 at 20:14
No ,there is no any errors. About HttpClient , I know but thanks.
– Victor Rodniansky
Nov 23 '18 at 22:11
No ,there is no any errors. About HttpClient , I know but thanks.
– Victor Rodniansky
Nov 23 '18 at 22:11
I don't see any code that would go out of angular's zone. If you initialize the message property in the constructor, are you able to see the message in the UI? There might be a disconnect between UI and the component class.
– Anjil Dhamala
Nov 24 '18 at 18:05
I don't see any code that would go out of angular's zone. If you initialize the message property in the constructor, are you able to see the message in the UI? There might be a disconnect between UI and the component class.
– Anjil Dhamala
Nov 24 '18 at 18:05
|
show 1 more comment
Try this and let me know.
- Make a property
loginRequest: Observable<any>;
- Inside
onSubmit()
:
onSubmit(request){
this.loginRequest = this.authService.login(request);
}
In your template,
<div>
{{ (loginRequest | async)?.msg }}
</div>
Here's a simple Http call.
import {HttpClient} from '@angular/common/http';
class SomeService {
constructor(private _http: HttpClient){}
postSomething() {
return this._http.post('url', toPost);
}
}
Thanks, unfortunately didn't help..
– Victor Rodniansky
Nov 22 '18 at 23:28
Where are you getting the httpPost() function from? That's not from Angular HttpClient. Your code might be going out of angular zone in that method.
– Anjil Dhamala
Nov 22 '18 at 23:29
Can you post your authService class along with the injections?
– Anjil Dhamala
Nov 22 '18 at 23:32
this post goes to NodeJs Api side..using ngZone.run .... didn't help too..
– Victor Rodniansky
Nov 22 '18 at 23:33
That doesn't help, Victor. I want to see your dependency Injections in AuthService class. Can you post your AuthService constructor?
– Anjil Dhamala
Nov 22 '18 at 23:35
|
show 1 more comment
Try this and let me know.
- Make a property
loginRequest: Observable<any>;
- Inside
onSubmit()
:
onSubmit(request){
this.loginRequest = this.authService.login(request);
}
In your template,
<div>
{{ (loginRequest | async)?.msg }}
</div>
Here's a simple Http call.
import {HttpClient} from '@angular/common/http';
class SomeService {
constructor(private _http: HttpClient){}
postSomething() {
return this._http.post('url', toPost);
}
}
Thanks, unfortunately didn't help..
– Victor Rodniansky
Nov 22 '18 at 23:28
Where are you getting the httpPost() function from? That's not from Angular HttpClient. Your code might be going out of angular zone in that method.
– Anjil Dhamala
Nov 22 '18 at 23:29
Can you post your authService class along with the injections?
– Anjil Dhamala
Nov 22 '18 at 23:32
this post goes to NodeJs Api side..using ngZone.run .... didn't help too..
– Victor Rodniansky
Nov 22 '18 at 23:33
That doesn't help, Victor. I want to see your dependency Injections in AuthService class. Can you post your AuthService constructor?
– Anjil Dhamala
Nov 22 '18 at 23:35
|
show 1 more comment
Try this and let me know.
- Make a property
loginRequest: Observable<any>;
- Inside
onSubmit()
:
onSubmit(request){
this.loginRequest = this.authService.login(request);
}
In your template,
<div>
{{ (loginRequest | async)?.msg }}
</div>
Here's a simple Http call.
import {HttpClient} from '@angular/common/http';
class SomeService {
constructor(private _http: HttpClient){}
postSomething() {
return this._http.post('url', toPost);
}
}
Try this and let me know.
- Make a property
loginRequest: Observable<any>;
- Inside
onSubmit()
:
onSubmit(request){
this.loginRequest = this.authService.login(request);
}
In your template,
<div>
{{ (loginRequest | async)?.msg }}
</div>
Here's a simple Http call.
import {HttpClient} from '@angular/common/http';
class SomeService {
constructor(private _http: HttpClient){}
postSomething() {
return this._http.post('url', toPost);
}
}
edited Nov 23 '18 at 3:51
answered Nov 22 '18 at 23:15
Anjil DhamalaAnjil Dhamala
6892922
6892922
Thanks, unfortunately didn't help..
– Victor Rodniansky
Nov 22 '18 at 23:28
Where are you getting the httpPost() function from? That's not from Angular HttpClient. Your code might be going out of angular zone in that method.
– Anjil Dhamala
Nov 22 '18 at 23:29
Can you post your authService class along with the injections?
– Anjil Dhamala
Nov 22 '18 at 23:32
this post goes to NodeJs Api side..using ngZone.run .... didn't help too..
– Victor Rodniansky
Nov 22 '18 at 23:33
That doesn't help, Victor. I want to see your dependency Injections in AuthService class. Can you post your AuthService constructor?
– Anjil Dhamala
Nov 22 '18 at 23:35
|
show 1 more comment
Thanks, unfortunately didn't help..
– Victor Rodniansky
Nov 22 '18 at 23:28
Where are you getting the httpPost() function from? That's not from Angular HttpClient. Your code might be going out of angular zone in that method.
– Anjil Dhamala
Nov 22 '18 at 23:29
Can you post your authService class along with the injections?
– Anjil Dhamala
Nov 22 '18 at 23:32
this post goes to NodeJs Api side..using ngZone.run .... didn't help too..
– Victor Rodniansky
Nov 22 '18 at 23:33
That doesn't help, Victor. I want to see your dependency Injections in AuthService class. Can you post your AuthService constructor?
– Anjil Dhamala
Nov 22 '18 at 23:35
Thanks, unfortunately didn't help..
– Victor Rodniansky
Nov 22 '18 at 23:28
Thanks, unfortunately didn't help..
– Victor Rodniansky
Nov 22 '18 at 23:28
Where are you getting the httpPost() function from? That's not from Angular HttpClient. Your code might be going out of angular zone in that method.
– Anjil Dhamala
Nov 22 '18 at 23:29
Where are you getting the httpPost() function from? That's not from Angular HttpClient. Your code might be going out of angular zone in that method.
– Anjil Dhamala
Nov 22 '18 at 23:29
Can you post your authService class along with the injections?
– Anjil Dhamala
Nov 22 '18 at 23:32
Can you post your authService class along with the injections?
– Anjil Dhamala
Nov 22 '18 at 23:32
this post goes to NodeJs Api side..using ngZone.run .... didn't help too..
– Victor Rodniansky
Nov 22 '18 at 23:33
this post goes to NodeJs Api side..using ngZone.run .... didn't help too..
– Victor Rodniansky
Nov 22 '18 at 23:33
That doesn't help, Victor. I want to see your dependency Injections in AuthService class. Can you post your AuthService constructor?
– Anjil Dhamala
Nov 22 '18 at 23:35
That doesn't help, Victor. I want to see your dependency Injections in AuthService class. Can you post your AuthService constructor?
– Anjil Dhamala
Nov 22 '18 at 23:35
|
show 1 more comment
I think it is a Zone related issue as you suggested..in that case:
onSubmit(request){
this.message="outer message"
this.loginRequest = this.authService.login(request);
this.loginRequest.subscribe((result) => {
if(result.msg){
this.message ="inner message"
// alert(this.message)
}
});
}
When onSubmit() fires , I see the "outer message" binding , but after entrance to subscription it disappears and the "inner message" is not shown at all.
add a comment |
I think it is a Zone related issue as you suggested..in that case:
onSubmit(request){
this.message="outer message"
this.loginRequest = this.authService.login(request);
this.loginRequest.subscribe((result) => {
if(result.msg){
this.message ="inner message"
// alert(this.message)
}
});
}
When onSubmit() fires , I see the "outer message" binding , but after entrance to subscription it disappears and the "inner message" is not shown at all.
add a comment |
I think it is a Zone related issue as you suggested..in that case:
onSubmit(request){
this.message="outer message"
this.loginRequest = this.authService.login(request);
this.loginRequest.subscribe((result) => {
if(result.msg){
this.message ="inner message"
// alert(this.message)
}
});
}
When onSubmit() fires , I see the "outer message" binding , but after entrance to subscription it disappears and the "inner message" is not shown at all.
I think it is a Zone related issue as you suggested..in that case:
onSubmit(request){
this.message="outer message"
this.loginRequest = this.authService.login(request);
this.loginRequest.subscribe((result) => {
if(result.msg){
this.message ="inner message"
// alert(this.message)
}
});
}
When onSubmit() fires , I see the "outer message" binding , but after entrance to subscription it disappears and the "inner message" is not shown at all.
onSubmit(request){
this.message="outer message"
this.loginRequest = this.authService.login(request);
this.loginRequest.subscribe((result) => {
if(result.msg){
this.message ="inner message"
// alert(this.message)
}
});
}
onSubmit(request){
this.message="outer message"
this.loginRequest = this.authService.login(request);
this.loginRequest.subscribe((result) => {
if(result.msg){
this.message ="inner message"
// alert(this.message)
}
});
}
answered Nov 23 '18 at 9:00
Victor RodnianskyVictor Rodniansky
5018
5018
add a comment |
add a comment |
I found the problem.
In my AuthService, in login() function, which returns an Observable, I am making a call for a this.routeAfterLogin(false) . This function redirects my route to login page in case the error occurs. That redirection inside an observable messes the change detection.
Actually I don't need it ,after removing it everything started to work fine.
Thanks all for the help.
public login(data): Observable<any> {
return this.rHttp.post(ApiRoutes.LoginRoute,data).pipe(map(result=>{
if(...){
// not relevant
}else{
let msg = "error message";
this.alertService.error(msg);
**this.routeAfterLogin(false);**
this.messageService.sendMessage('',Events.UserLogout);
return {msg:msg};
}
}));
}
**private routeAfterLogin(state:boolean)** {
this.userIsLoggedIn = state;
if(this.userIsLoggedIn){
this.router.navigate(['/home']);
console.log("Login");
} else {
this.router.navigate(['/login']);
console.log("Failure Login");
}
}
add a comment |
I found the problem.
In my AuthService, in login() function, which returns an Observable, I am making a call for a this.routeAfterLogin(false) . This function redirects my route to login page in case the error occurs. That redirection inside an observable messes the change detection.
Actually I don't need it ,after removing it everything started to work fine.
Thanks all for the help.
public login(data): Observable<any> {
return this.rHttp.post(ApiRoutes.LoginRoute,data).pipe(map(result=>{
if(...){
// not relevant
}else{
let msg = "error message";
this.alertService.error(msg);
**this.routeAfterLogin(false);**
this.messageService.sendMessage('',Events.UserLogout);
return {msg:msg};
}
}));
}
**private routeAfterLogin(state:boolean)** {
this.userIsLoggedIn = state;
if(this.userIsLoggedIn){
this.router.navigate(['/home']);
console.log("Login");
} else {
this.router.navigate(['/login']);
console.log("Failure Login");
}
}
add a comment |
I found the problem.
In my AuthService, in login() function, which returns an Observable, I am making a call for a this.routeAfterLogin(false) . This function redirects my route to login page in case the error occurs. That redirection inside an observable messes the change detection.
Actually I don't need it ,after removing it everything started to work fine.
Thanks all for the help.
public login(data): Observable<any> {
return this.rHttp.post(ApiRoutes.LoginRoute,data).pipe(map(result=>{
if(...){
// not relevant
}else{
let msg = "error message";
this.alertService.error(msg);
**this.routeAfterLogin(false);**
this.messageService.sendMessage('',Events.UserLogout);
return {msg:msg};
}
}));
}
**private routeAfterLogin(state:boolean)** {
this.userIsLoggedIn = state;
if(this.userIsLoggedIn){
this.router.navigate(['/home']);
console.log("Login");
} else {
this.router.navigate(['/login']);
console.log("Failure Login");
}
}
I found the problem.
In my AuthService, in login() function, which returns an Observable, I am making a call for a this.routeAfterLogin(false) . This function redirects my route to login page in case the error occurs. That redirection inside an observable messes the change detection.
Actually I don't need it ,after removing it everything started to work fine.
Thanks all for the help.
public login(data): Observable<any> {
return this.rHttp.post(ApiRoutes.LoginRoute,data).pipe(map(result=>{
if(...){
// not relevant
}else{
let msg = "error message";
this.alertService.error(msg);
**this.routeAfterLogin(false);**
this.messageService.sendMessage('',Events.UserLogout);
return {msg:msg};
}
}));
}
**private routeAfterLogin(state:boolean)** {
this.userIsLoggedIn = state;
if(this.userIsLoggedIn){
this.router.navigate(['/home']);
console.log("Login");
} else {
this.router.navigate(['/login']);
console.log("Failure Login");
}
}
public login(data): Observable<any> {
return this.rHttp.post(ApiRoutes.LoginRoute,data).pipe(map(result=>{
if(...){
// not relevant
}else{
let msg = "error message";
this.alertService.error(msg);
**this.routeAfterLogin(false);**
this.messageService.sendMessage('',Events.UserLogout);
return {msg:msg};
}
}));
}
**private routeAfterLogin(state:boolean)** {
this.userIsLoggedIn = state;
if(this.userIsLoggedIn){
this.router.navigate(['/home']);
console.log("Login");
} else {
this.router.navigate(['/login']);
console.log("Failure Login");
}
}
public login(data): Observable<any> {
return this.rHttp.post(ApiRoutes.LoginRoute,data).pipe(map(result=>{
if(...){
// not relevant
}else{
let msg = "error message";
this.alertService.error(msg);
**this.routeAfterLogin(false);**
this.messageService.sendMessage('',Events.UserLogout);
return {msg:msg};
}
}));
}
**private routeAfterLogin(state:boolean)** {
this.userIsLoggedIn = state;
if(this.userIsLoggedIn){
this.router.navigate(['/home']);
console.log("Login");
} else {
this.router.navigate(['/login']);
console.log("Failure Login");
}
}
answered Nov 23 '18 at 15:18
Victor RodnianskyVictor Rodniansky
5018
5018
add a comment |
add a comment |
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53438210%2fhow-can-i-bind-from-a-callback-in-angular-4%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
could you create a stackblitz snippet for this ?
– Korte
Nov 22 '18 at 22:34