Problem with sending data by post, router error - angular7

I can't send data to backend I don't know why, the problem in the console looks like that exactly at the login and register component this same issue is appearing. Maybe the ngsubmit is formated wrong but I don't know how to post the (ngSubmit)="onSubmit(f)" by the patter that it needs to represent.
This is the error in the console and the components which I'm using.
TypeError: Cannot set property 'router' of undefined
at AuthInceptor (auth.interceptor.ts:11)
at eval (module.ngfactory.js? [sm]:1)
at _callFactory (core.js:21283)
at _createProviderInstance (core.js:21237)
at resolveNgModuleDep (core.js:21198)
at NgModuleRef_.push../node_modules/#angular/core/fesm5/core.js.NgModuleRef_.get
auth.service.ts
constructor(private router: Router, private httpClient: HttpClient) {}
LogIn(email: string, password: string) {
const reqHeader = new HttpHeaders({'Content-Type': 'application/json', 'No-Auth': 'True'});
return this.httpClient.post<any>(this.apiAddress + 'account/login', {
Email: email,
Password: password
}, {headers: reqHeader})
.catch((e: any) => Observable.throw(this.errorHandler(e)));
}
Register(name: string, email: string, password: string, role: string) {
const reqHeader = new HttpHeaders({'Content-Type': 'application/json', 'No-Auth': 'True'});
return this.httpClient.post<any>(this.apiAddress + 'account/register', {
Name: name,
Email: email,
Password: password,
Role: role
}, {headers: reqHeader})
.catch((e: any) => Observable.throw(this.errorHandler(e)));
}
errorHandler(error: any): void {
console.log(error);
}
auth.inceptor.ts
constructor(private router: Router) { }
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
if (req.headers.get('No-Auth') === 'True') {
return next.handle(req.clone());
}
if (localStorage.getItem('userToken') != null) {
const clonedreq = req.clone({
headers: req.headers.set('Authorization', 'Bearer ' + localStorage.getItem('userToken'))
});
return next.handle(clonedreq)
.do(
succ => { },
err => {
if (err.status === 401) {
this.router.navigate(['/login']);
}
}
);
} else {
this.router.navigate(['/login']);
}
}
log-in form
<form class="example-form" (ngSubmit)="onSubmit(email.value, password.value)" #f="ngForm">
<mat-card-content>
<table class="example-full-width" cellspacing="0">
<tr>
<td>
<mat-form-field class="example-full-width">
<input matInput placeholder="Email" #email ngModel name="email" required>
</mat-form-field>
</td>
</tr>
<tr>
<td><mat-form-field class="example-full-width">
<input matInput placeholder="Password" #password ngModel type="password" name="password" required>
</mat-form-field></td>
</tr></table>
</mat-card-content>
<mat-card-actions>
<button mat-raised-button type="submit" color="primary">Login</button>
<div *ngIf="isLoginError" class="red-text center error-message">Error Incorrect email or password</div>
</mat-card-actions>
</form>
Submit function
onSubmit(email, password): void {
this.authService.LogIn(email, password)
.subscribe((data: any) => {
localStorage.setItem('userToken', data.token);
localStorage.setItem('role', data.role);
this.router.navigate(['../Home']);
console.log(data);
},
(err: HttpErrorResponse) => {
this.isLoginError = true;
});
}

Related

EXCEPTION in Angular 8: Can't resolve all parameters Angular 8

I've built a app in Angular 8, but I have encountered a strange issue where I cannot inject a service into one of my components. Basically i want to show all my login/register means under one page without routing by just managing fields. But this error is coming up again and again.
Uncaught Error: Can't resolve all parameters for AuthTestComponent: ([object Object], [object Object], ?).
My auth.service.ts file:-
import { Injectable } from '#angular/core';
import { HttpClient, HttpErrorResponse } from '#angular/common/http';
import { catchError } from 'rxjs/operators';
import { throwError } from 'rxjs';
import { Router } from '#angular/router'
#Injectable({
providedIn: 'root'
})
export class AuthService {
authUrl = "API"
constructor(private http: HttpClient, private router: Router) { }
registerUser(email: string, password: string) {
return this.http.post<any>(this.authUrl + "user-register", {
email: email,
password: password,
// c_password: password,
token: true
}).pipe(catchError(this.handleError))
}
LoginUser(email: string, password: string) {
return this.http.post<any>(this.authUrl + "user-login", {
email: email,
password: password,
access_token: true
}).pipe(catchError(this.handleError))
}
loggedIn() {
return !!localStorage.getItem('access_token')
}
getToken() {
return localStorage.getItem('access_token')
}
logoutUser() {
localStorage.removeItem('access_token');
this.router.navigate(['login'])
}
private handleError(errorRes: HttpErrorResponse) {
let errorMessage = "An Unkown error occured!";
if (!errorRes.error.error.errors || !errorRes.error.error.email[0]) {
return throwError(errorMessage)
}
switch (errorRes.error.error.email[0]) {
case 'The email has already been taken.':
errorMessage = 'The email already exists!'
break;
}
// switch (errorRes.error.error[0]) {
// case 'Password or Email not matched':
// errorMessage = 'Please Sign Up to continue!'
// case 'INVALID_PASSWORD':
// errorMessage = 'This password is not correct.'
// }
return throwError(errorMessage);
}
sendPasswordResetLink(email: string) {
return this.http.post<any>(this.authUrl + "updatepassword", {
email: email
}).pipe(catchError(this.handleError))
}
}
My component file:-
import { Component, Inject } from '#angular/core';
import { FormGroup, FormControl, Validators } from '#angular/forms';
// import { MatDialogRef, MAT_DIALOG_DATA } from '#angular/material/dialog';
import { $animations } from './login-animations';
import { $providers } from './login-providers';
import { $pages } from './login-pages';
import { from } from 'rxjs';
import { AuthService } from '../services/auth/auth.service';
import { Router } from '#angular/router';
export type loginAction = 'register' | 'signIn' | 'forgotPassword' | 'signOut';
#Component({
selector: 'app-auth-test',
templateUrl: './auth-test.component.html',
styleUrls: ['./auth-test.component.css'],
animations: $animations
})
export class AuthTestComponent {
readonly providers = $providers;
private pages = $pages;
private page: loginAction;
// private code: string;
readonly form: FormGroup;
// private password2: FormControl;
private email: FormControl;
private password: FormControl;
public error = null;
// private newPassword: FormControl;
isLoading = false;
public progress = false;
constructor(private auth: AuthService, private router: Router, private action: loginAction) {
// Form controls
// this.password2 = new FormControl(null, Validators.required);
this.email = new FormControl(null, [Validators.required, Validators.email]);
this.password = new FormControl(null, Validators.required);
// this.newPassword = new FormControl(null, Validators.required);
// Empty form group
this.form = new FormGroup({});
// Populates the form according to the page
this.switchPage(this.page = action);
}
get currentPage() { return this.pages[this.page || 'signIn']; }
private switchPage(page: loginAction) {
// Removes all the controls from the form group
Object.keys(this.form.controls).forEach(control => {
this.form.removeControl(control);
});
// Add the relevant controls to the form according to selected page
switch (this.page = page) {
case 'register':
this.form.addControl('email', this.email);
this.form.addControl('password', this.password);
// this.form.addControl('password2', this.password2);
break;
default:
// case 'signIn':
// this.form.addControl('email', this.email);
// this.form.addControl('password', this.password);
// break;
// case 'forgotPassword':
// this.form.addControl('email', this.email);
// break;
/*
case 'resetPassword':
this.form.addControl('newPassword', this.newPassword);
break;
*/
}
}
// private showError(error: string) {
// this.error = error;
// this.progress = false;
// setTimeout(() => this.error = null, 5000);
// }
public activate(action: loginAction) {
this.progress = true;
switch (action) {
default:
// case 'signIn':
// this.signIn(this.email.value, this.password.value);
// break;
case 'register':
this.registerNew(this.email.value, this.password.value);
break;
// case 'forgotPassword':
// this.forgotPassword(this.email.value);
// break;
/*
case 'resetPassword':
this.resetPassword( this.code, this.newPassword.value );
break;
*/
}
}
private registerNew(email: string, password: string) {
// Registering a new user with a email/password
this.auth.registerUser(email, password).subscribe(
res => {
console.log(res);
localStorage.setItem('token', res.token)
this.isLoading = false;
this.router.navigate(['login']);
},
errorMessage => {
console.log(errorMessage);
this.error = errorMessage;
this.isLoading = false;
}
);
}
}
HTML form file -:
<div [#vanish]="page">
<h1 class="mat-title">{{ currentPage.title }}</h1>
<p class="mat-small">{{ currentPage.message }}</p>
</div>
<form [formGroup]="form" fxLayout="column" fxLayoutAlign="space-around stretch" fxLayoutGap="10px"
(ngSubmit)="activate(page)" *ngIf="page !== 'promptEmail' && page !== 'verifyEmail' && page !== 'recoverEmail'">
<!-- ERROR MESSAGE -->
<mat-error *ngIf="error" #inflate>{{ error }}</mat-error>
<!-- NAME
<mat-form-field appearance="legacy" *ngIf="form.contains('confirm')" #inflate>
<mat-label>Full name</mat-label>
<input matInput formControlName="confirm">
<mat-error *ngIf="form.controls.confirm.errors?.required">
Please specify your name here
</mat-error>
</mat-form-field> -->
<!-- EMAIL -->
<mat-form-field appearance="legacy" *ngIf="form.contains('email')" #inflate>
<mat-label>Email</mat-label>
<input matInput formControlName="email">
<mat-error *ngIf="form.controls.email.errors?.required">
Please specify an email address
</mat-error>
<mat-error *ngIf="form.controls.email.errors?.email">
Ooops! it looks like this is not a valid email
</mat-error>
</mat-form-field>
<!-- PASSWORD -->
<mat-form-field appearance="legacy" *ngIf="form.contains('password')" #inflate>
<mat-label>Password</mat-label>
<input matInput [type]="hidePassword ? 'password' : 'text'" formControlName="password">
<mat-icon matSuffix (click)="hidePassword = !hidePassword">
{{ hidePassword ? 'visibility_off' : 'visibility'}}
</mat-icon>
<mat-error *ngIf="form.controls.password.errors?.required">
A password is required
</mat-error>
</mat-form-field>
<!-- confirm PASSWORD -->
<mat-form-field appearance="legacy" *ngIf="form.contains('password')" #inflate>
<mat-label>Password</mat-label>
<input matInput [type]="hidePassword ? 'password' : 'text'" formControlName="password2">
<mat-icon matSuffix (click)="hidePassword = !hidePassword">
{{ hidePassword ? 'visibility_off' : 'visibility'}}
</mat-icon>
<mat-error *ngIf="form.controls.password2.errors?.required">
A password is required
</mat-error>
<mat-hint class="mat-link" align="end" (click)="switchPage('forgotPassword')" *ngIf="page == 'signIn'"
#inflate>Forgot password?</mat-hint>
</mat-form-field>
<!-- NEW EMAIL -->
<!-- <mat-form-field appearance="legacy" *ngIf="form.contains('newEmail')" #inflate>
<mat-label>New email</mat-label>
<input matInput formControlName="newEmail">
<mat-error *ngIf="form.controls.newEmail.errors?.required">
A new email is required
</mat-error>
<mat-error *ngIf="form.controls.newEmail.errors?.email">
This email looks wrong
</mat-error>
</mat-form-field> -->
<!-- NEW PASSWORD -->
<!-- <mat-form-field appearance="legacy" *ngIf="form.contains('newPassword')" #inflate>
<mat-label>New password</mat-label>
<input matInput formControlName="newPassword">
<mat-error *ngIf="form.controls.newPassword.errors?.required">
A new password is required
</mat-error>
</mat-form-field> -->
<!-- ACTION BUTTON -->
<button mat-stroked-button color="primary" type="submit" [disabled]="!form.valid" class="btn">
{{ currentPage.caption }}
</button>
<mat-progress-bar *ngIf="progress" mode="indeterminate" #inflate></mat-progress-bar>
</form>
<p class="mat-small" *ngIf="page == 'signIn'">
Are you a new user? <span class="mat-link" (click)="switchPage('register')">Register</span>
</p>
<p class="mat-small" *ngIf="page === 'register' || page === 'forgotPassword'">
Already have login and password? <span class="mat-link" (click)="switchPage('signIn')">Sign-in</span>
</p>
<!-- SIGN-IN PROVIDERS -->
<div fxLayout="column" fxLayoutAlign="center center" *ngIf="page == 'signIn'" #inflate>
<p class="mat-small">or sign-in with:</p>
<div fxLayout="row wrap" fxLayoutAlign="center center" fxLayoutGap="10px">
<button mat-icon-button *ngFor="let p of providers" (click)="signInWith(p.name)">
<mat-icon class="providers" [fontSet]="p.icon.split(':')[0]" [fontIcon]="p.icon.split(':')[1]"
[ngStyle]="{ color: p.color }">
</mat-icon>
</button>
</div>
</div>
The error trace provides a clue about what's going on: ([object Object], [object Object], ?). In Angular, it's objects all the way down (even a module is just some syntatical sugar around an object).
Since the first items in the error messages are objects, we can assume that dependency injection was successful for first two services referenced in the constructor. The ? in the error message (the third position) indicates there may be an issue with injecting the final dependency, i.e., private action: loginAction.
The Angular guide on dependency injection (DI) provides some context for how it operates by calling out that "dependencies are services or objects". The error you're seeing might be caused by trying to inject a non-injectable entity, i.e., a string.
It might be helpful to see how the component is implemented in your code, e.g., the corresponding HTML. Aside from the InjectionToken example provided in one of the other responses, you might also investigate whether an Input property (see Angular Input on the component allows you to pass the necessary page action).
Seems like the problem is here:
private action: loginAction
loginAction is a type and can not be injected.
For example, you can use InjectionToken
const LOGIN_ACTION = new InjectionToken<loginAction>('Login action token');
...
#Inject(LOGIN_ACTION) private action: loginAction

TypeError (no implicit conversion of String into Integer): Rails 6

I'm trying to connect a frontend react app with a rails api backend and I'm having this error
Completed 500 Internal Server Error in 36844ms (ActiveRecord: 0.0ms | Allocations: 31928) TypeError (no implicit conversion of String into Integer): app/controllers/registrations_controller.rb:9:in `[]' app/controllers/registrations_controller.rb:9:in `create'
The api server is on localhost:3001 and the react app on localhost:3000
This is my registrations controller:
class RegistrationsController < ApplicationController
def create
newUser = User.create!(
first_name: params["newUser"]["first_name"],
last_name: params["newUser"]["last_name"],
email: params["newUser"]["email"],
password: params["newUser"]["password"],
password_confirmation: ["newUser"]["password_confirmation"],
role: ["newUser"]["role"]
)
byebug
# Usuario creado
if newUser
render json: {
status: :created,
newUser: newUser
}
else
render json: {
status: 500
}
end
end
end
And this is my react component that makes the post request to the backend:
import React, { Component } from "react";
import axios from "axios";
class Registration extends Component {
constructor(props) {
super(props);
this.state = {
first_name: "",
last_name: "",
email: "",
password: "",
password_confirmation: "",
errors: "",
role: "user"
};
this.handleSubmit = this.handleSubmit.bind(this);
this.handleChange = this.handleChange.bind(this);
}
handleSubmit(evt) {
evt.preventDefault();
console.log(this.state);
axios
.post(
"http://localhost:3001/registrations",
{
newUser: {
first_name: this.state.first_name,
last_name: this.state.last_name,
email: this.state.email,
password: this.state.password,
password_confirmation: this.state.password_confirmation,
role: this.state.role
}
},
{ withCredentials: true }
)
.then(res => console.log("Registro exitoso", res))
.catch(err => console.log("Error en el registrio", err));
}
handleChange(evt) {
evt.preventDefault();
this.setState({
[evt.target.name]: event.target.value
});
console.log("On change");
}
render() {
return (
<div>
<form onSubmit={this.handleSubmit}>
<input
type="text"
name="first_name"
placeholder="Nombre"
value={this.state.first_name}
onChange={this.handleChange}
/>
<input
type="text"
name="last_name"
placeholder="apellido"
value={this.state.last_name}
onChange={this.handleChange}
/>
<input
type="email"
name="email"
placeholder="usuario#dominio.com"
value={this.state.email}
onChange={this.handleChange}
/>
<input
type="password"
name="password"
placeholder="Contraseña"
value={this.state.password}
onChange={this.handleChange}
/>
<input
type="password"
name="password_confirmation"
placeholder="Confirmar contraseña"
value={this.state.password_confirmation}
onChange={this.handleChange}
/>
<select name="role" value={this.state.role} onChange={this.handleChange}>
<option value="user">Usuario</option>
<option value="admin">Administrador</option>
</select>
<button type="submit">Registrar!</button>
</form>
</div>
);
}
}
export default Registration;
Why am i having this error? I checked types of the variables inside the newUser object both from byebug and debugger. Thanks in advance for any help!
Maybe this:
password_confirmation: ["newUser"]["password_confirmation"],
...should be:
password_confirmation: params["newUser"]["password_confirmation"],
And this:
role: ["newUser"]["role"]
...should be:
role: params["newUser"]["role"]

Use custom constraint in bootstrapValidator

I want to add some custom constraint to password validation. I want it to have at least a Lowercase and an uppercase and a digit.
<form id="userForm">
<input type="hidden" class="form-control" id="ID" />
<div class="row">
<div class="col-sm-12 col-md-6 col-lg-6">
<div class="form-group">
<label for="FName">First Name</label>
<input type="text" class="form-control" id="FName" name="FName" />
</div>
</div>
<div class="col-sm-12 col-md-6 col-lg-6">
<div class="form-group">
<label for="LName">Last Name</label>
<input type="text" class="form-control" id="LName" name="LName" />
</div>
</div>
</div>
<div class="row">
<div class="col-sm-12 col-md-6 col-lg-6">
<div class="form-group">
<label for="UserName">User Name </label>
<input type="text" class="form-control" id="UserName" name="UserName" />
</div>
</div>
<div class="col-sm-12 col-md-6 col-lg-6">
<div class="form-group">
<label for="Password">Password </label>
<input type="password" class="form-control" id="Password" name="Password" />
</div>
</div>
</div>
</form>
<script type="text/javascript">
$('#userForm').bootstrapValidator({
message: 'This value is not valid',
feedbackIcons: {
valid: 'glyphicon glyphicon-ok',
invalid: 'glyphicon glyphicon-remove',
validating: 'glyphicon glyphicon-refresh'
},
submitHandler: function (validator, form, submitButton) {
},
fields: {
FName: {
validators: {
notEmpty: {
message: 'Required!'
}
}
},
LName: {
validators: {
notEmpty: {
message: 'Required!'
}
}
},
UserName: {
validators: {
notEmpty: {
message: 'Required!'
}
},
stringLength: {
min: 3,
max: 25,
message: 'Length should be between 3 to 25.'
},
},
Password: {
validators: {
notEmpty: {
message: 'Required!'
},
stringLength: {
min: 8,
max: 15,
message: 'Length should be between 8 to 15.'
}
}
},
}
});
</script>
I used callback at last:
$('#userForm').bootstrapValidator({
message: 'This value is not valid',
feedbackIcons: {
valid: 'glyphicon glyphicon-ok',
invalid: 'glyphicon glyphicon-remove',
validating: 'glyphicon glyphicon-refresh'
},
submitHandler: function (validator, form, submitButton) {
},
excluded: [':disabled'],
fields: {
FName: {
validators: {
notEmpty: {
message: 'Required!'
}
}
},
LName: {
validators: {
notEmpty: {
message: 'Required!'
}
}
},
UserName: {
validators: {
notEmpty: {
message: 'Required!'
},
stringLength: {
min: 3,
max: 25,
message: 'Length should be between 3 to 25.'
}
}
},
Password: {
validators: {
notEmpty: {
message: 'Required!'
},
stringLength: {
min: 8,
max: 15,
message: 'Length should be between 8 to 5.'
},
callback: {
callback: function (value, validator, $field) {
var validv = true;
var messagev = '';
//Number
if (!value.match(/\d/)) {
validv = false;
messagev += 'Enter a number.<br />'
}
//Lowercase letter
if (!value.match(/[A-z]/)) {
validv = false;
messagev += 'Enter a lowercase charachter..<br />'
}
//Capital letter
if (!value.match(/[A-Z]/)) {
validv = false;
messagev += 'Enter a capital charachter.'
}
return {
valid: validv,
message: messagev
}
}
}
}
},
selectStatus: {
validators: {
notEmpty: {
message: 'Required!'
}
}
}
}
});
You can use below code for validation of password for Upper case, Lower case, and digit.
Where Value = field name you can add this code into Password Field.
// The password doesn't contain any uppercase character
if (value === value.toLowerCase()) {
return {
valid: false,
message: 'The password must contain at least one upper case character'
}
}
// The password doesn't contain any uppercase character
if (value === value.toUpperCase()) {
return {
valid: false,
message: 'The password must contain at least one lower case character'
}
}
// The password doesn't contain any digit
if (value.search(/[0-9]/) < 0) {
return {
valid: false,
message: 'The password must contain at least one digit'
}
}

React Axios to Rails Knock

I am trying to send a POST request from axios to a Rails API using the following function in the React frontend:
export function registerUser({ name, email, password }) {
var postdata = JSON.stringify({
auth: {
name, email, password
}
});
return function(dispatch) {
axios.post(`${API_URL}/user_token`, postdata )
.then(response => {
cookie.save('token', response.data.token, { path: '/' });
dispatch({ type: AUTH_USER });
window.location.href = CLIENT_ROOT_URL + '/dashboard';
})
.catch((error) => {
errorHandler(dispatch, error.response, AUTH_ERROR)
});
}
}
The Knock gem expects the request in the following format:
{"auth": {"email": "foo#bar.com", "password": "secret"}}
My current function seem to generate the correct format (inspecting the request in the browser devtools), but I'm getting the following error:
Uncaught (in promise) Error: Objects are not valid as a React child
(found: object with keys {data, status, statusText, headers, config,
request}). If you meant to render a collection of children, use an
array instead or wrap the object using createFragment(object) from the
React add-ons. Check the render method of Register.
class Register extends Component {
handleFormSubmit(formProps) {
this.props.registerUser(formProps);
}
renderAlert() {
if(this.props.errorMessage) {
return (
<div>
<span><strong>Error!</strong> {this.props.errorMessage}</span>
</div>
);
}
}
render() {
const { handleSubmit } = this.props;
return (
<form onSubmit={handleSubmit(this.handleFormSubmit.bind(this))}>
{this.renderAlert()}
<div className="row">
<div className="col-md-6">
<label>Name</label>
<Field name="name" className="form-control" component={renderField} type="text" />
</div>
</div>
<div className="row">
<div className="col-md-12">
<label>Email</label>
<Field name="email" className="form-control" component={renderField} type="text" />
</div>
</div>
<div className="row">
<div className="col-md-12">
<label>Password</label>
<Field name="password" className="form-control" component={renderField} type="password" />
</div>
</div>
<button type="submit" className="btn btn-primary">Register</button>
</form>
);
}
}
The error is caused by the following line in your code
errorHandler(dispatch, error.response, AUTH_ERROR)
The exception raised clearly explains that. Instead of setting error.response, try to use the actual data from error.response. E.g error.response.data. Also, you can try replacing the error.response with a string and see how that behaves, then reference the string you need from error.response.data.

Knockout checkbox binding, with autoupdate

I am trying to when a person changes the state of previously bound checkbox, I want to update the server with the new value.
So here is what I have:
JSCRIPT
function JobViewModel() {
var self = this;
var baseUri = '/Api/Pedidos/';
self.TotalItems = ko.observable(#Model.TotalItems);
self.AbreviaNome = ko.observable(#Model.AbreviaNome.ToString().ToLower());
self.AbreviaFantasia = ko.observable(#Model.AbreviaFantasia.ToString().ToLower());
self.update = function () {
alert('Boom');
$.ajax({
type: "PUT",
url: baseUri,
data: self.Job,
datatype: "json",
contenttype: "application/json"
})
.done(function (data) {
//handleSuccessFunctionHERE(data);
alert('Magic');
})
.error(function (jqXHR, textStatus, errorThrown) {
alert(errorThrown);
alert("fail");
});
};
}
function JobDetailsViewModel() {
var self = this;
var baseUri = '/Api/Pedidos/';
self.Job = new JobViewModel();
}
HTML
<label class="btn btn-primary" data-bind="css: {active:Job.AbreviaNome }">
<input type="checkbox" data-bind="checked: AbreviaNome , onchange: Job.update" name="type" id="AbreviaNome "> Nome</input>
</label>
This never triggers the update function. I also have tried :
<label class="btn btn-primary" data-bind="css: {active:Job.AbreviaNome }">
<input type="checkbox" data-bind="checked: AbreviaNome , click: Job.update" name="type" id="AbreviaNome "> Nome</input>
</label>
And this within the JobViewModel:
this.AbreviaNome.subscribe(function (newValue) {
alert('test');
}, this);
Any ideas?
You should use subscribe for this and not the onchange handler. You mentioned you tried it, but you subscribed to AbreviaNome instead of AbreviaLogradouro.
Solved the problem, below is the binding:
<label class="btn btn-primary " data-bind="css: {active:Job.AbreviaNome}">
<input type="checkbox" data-bind="checked: Job.AbreviaNome, event: {change: Job.update}" name="type" id="AbreviaNome">Nome/Razão</input>
</label>
Not sure this was the best way but it works.

Resources