简体   繁体   中英

Unexpected end of json input

I am trying to display an alert after a user is registered. I have tried debugging and understood that it is going to error function always ( When a user is registered successfully and a user already exists).

Below is my code. I am not able to understood why is it always going into error. Any help is appreciated since I am stuck with this from long time. Thanks in advance.

1)Alert Component

import { AlertService } from './../../shared/services/alert.service';
import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'app-alert',
  templateUrl: './alert.component.html',
  styleUrls: ['./alert.component.css']
})
export class AlertComponent  {

  private _alertService;
  private message: any;

  constructor(alertService: AlertService) {
    this._alertService = alertService;

  }

   ngOnInit() {
       this._alertService.getMessage().subscribe(message => { this.message = message; });
     }

}

2.Alert Template

<div *ngIf="message" [ngClass]="{ 'alert': message, 'alert-success': message.type === 'success', 
       'alert-danger': message.type === 'error' }">{{message.text}}</div>

3)Register Template

<div class="container">

    <h2>Register</h2>
    <form name="form" (ngSubmit)="f.form.valid && register()" #f="ngForm" novalidate>
        <div class="form-group" [ngClass]="{ 'has-error': f.submitted && !username.valid }">
            <label for="username">Username</label>
            <input type="text" class="form-control" name="username" [(ngModel)]="model.username" #username="ngModel" required />
            <div *ngIf="f.submitted && !username.valid" class="help-block">Username is required</div>
        </div>
        <div class="form-group" [ngClass]="{ 'has-error': f.submitted && !password.valid }">
            <label for="password">Password</label>
            <input type="password" class="form-control" name="password" [(ngModel)]="model.password" #password="ngModel" required minlength="10" />
            <div *ngIf="f.submitted && !password.valid" class="help-block"> Password is required (minimum 10 characters)</div>
        </div>
        <div class="form-group">
            <button  class="btn btn-primary" (click)="registerUser()">Register</button>
              <app-alert></app-alert>
            <a [routerLink]="['']" class="btn btn-link">Cancel</a>
        </div>

    </form>
</div>

4)Register Component

import { AlertService } from './../../shared/services/alert.service';
import { RegisterService } from './../../shared/services/register.service';
import { Observable } from 'rxjs/Observable';
import { Component, OnInit } from '@angular/core';
import { Router, ActivatedRoute } from '@angular/router';
import { AuthService } from '../../shared/services/index';
import { Http, Request, RequestMethod, RequestOptions, Headers, Response } from '@angular/http';
@Component({
  selector: 'app-register',
  templateUrl: './register.component.html',
  styleUrls: ['./register.component.css']
})
export class RegisterComponent implements OnInit {
   private  _authService: AuthService;
   private  _alertService: AlertService;
    private  _regsiterService: RegisterService;
    private appContent = 'application/json';
    private _router: Router;
   private baseUrl = 'http://localhost:5000/api/v1/';
   model: any = {};
    username: string;
    password: string;

   constructor(authService: AuthService, http: Http, router: Router, registerService: RegisterService, alertService: AlertService) {
   this._authService = authService;
   this._regsiterService = registerService;
   this._router = router;
   this._alertService = alertService;
  }

  ngOnInit() {
  }
        registerUser() {
        this._regsiterService.registerUser(this.model.username, this.model.password)
            .subscribe(
                data => {
                    console.log('Calling alert');
                    this._alertService.success('Registration Successful');
                    this._router.navigate(['/login']);
                },
                error => {
                      console.log('Calling alert');
                   //  this._alertService.error(error);
                });
    }

}

5)Alert Service

import { Injectable } from '@angular/core';
import { Observable } from 'rxjs/Observable';
import {Subject} from 'rxjs/Subject';


@Injectable()
// Checks if a user is a authenticated user and has the valid token without expiration.
export class AlertService {

      private subject = new Subject<any>();
      success(message: string) {
          console.log('Registration Successful');
         this.subject.next({ type: 'success', text: message });
       }
    //    error(message: string) {
    //           console.log('Registration Failed');
    //     this.subject.next({ type: 'error', text: message });
    // }
       getMessage(): Observable<any> { return this.subject.asObservable(); }
}

Below is the Error Screenshot

JSON输入意外结束

In your html you have:

(ngSubmit)="f.form.valid && register()"

But your method is:

registerUser() {
    // ..
}

So the angular parser cannot find the register method that is defined in your html.

Unexpected end of json input

This error normally happens when you have a http call that gets failed for whatever reason ( wrong url, server is down, port is closed, ) and the returned response from the server is not a JSON .

Have a look at your network tab and see the http cal that you're making, what is that you're getting in the response tab.

Basically this error generally means, Javascript hasn't been able to parse something that it was meant to be JSON

If I were you I would check for typos in the template and ts file.

Also, you can try to just import the services at the top of the file and just add them in the constructor like this :

constructor(private authService: AuthService, private http: Http, private router: Router, private registerService: RegisterService, private alertService: AlertService) { }

I think TS will do the assignment for you. Then onInit() or any other place you can write this.authService.someMethod() etc.

For sure the "not a function" error indicates misspelling/typo.

As it is mentioned already register() exist in your html template but not in the ts file. I would rename the properties of the RegisterComponent also to make sure that possible typos and bugs would be avoided in the future.

The Unexpected end of json input might be due to the fact that you are not providing a valid json from your server. I haven't seen the code inside this._regsiterService.registerUser . But I believe there's a response.json() call that causes the issue.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM