简体   繁体   English

json输入的意外结束

[英]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 1)警报组件

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 2.Alert模板

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

3)Register Template 3)注册模板

<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 4)注册组件

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 5)警报服务

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: 在你的HTML中你有:

(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. 因此角度解析器找不到html中定义的register方法。

Unexpected end of json input json输入的意外结束

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 . 当您的http调用由于某种原因(错误的URL,服务器关闭,端口关闭)而失败并且从服务器返回的响应不是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. 查看您的网络选项卡,查看您正在制作的http cal,以及您在响应选项卡中获得的内容。

Basically this error generally means, Javascript hasn't been able to parse something that it was meant to be JSON 基本上这个错误通常意味着,Javascript无法解析它本来就是JSON

If I were you I would check for typos in the template and ts file. 如果我是你,我会检查模板和ts文件中的拼写错误。

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. 我想TS会为你做作业。 Then onInit() or any other place you can write this.authService.someMethod() etc. 然后onInit()或任何其他地方你可以写this.authService.someMethod()等。

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. 正如前面提到的那样, register()存在于你的html模板中但不存在于ts文件中。 I would rename the properties of the RegisterComponent also to make sure that possible typos and bugs would be avoided in the future. 我还会重命名RegisterComponent的属性,以确保将来可以避免可能的拼写错误和错误。

The Unexpected end of json input might be due to the fact that you are not providing a valid json from your server. Unexpected end of json inputUnexpected end of json input可能是因为您没有从服务器提供有效的json。 I haven't seen the code inside this._regsiterService.registerUser . 我还没有看到this._regsiterService.registerUser的代码。 But I believe there's a response.json() call that causes the issue. 但我相信有一个response.json()调用导致问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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