意外结束json输入

时间:2017-08-24 18:28:48

标签: javascript angular

我正在尝试在用户注册后显示警报。我已经尝试过调试,并且明白它总是会出现错误功能(当用户注册成功并且用户已经存在时)。

以下是我的代码。我无法理解为什么总是会出错。 任何帮助都表示赞赏,因为我长期坚持这一点。提前谢谢。

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

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

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

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

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(); }
}

以下是错误屏幕截图

Unexpected end of JSON input

4 个答案:

答案 0 :(得分:5)

在您的HTML中,您有:

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

但你的方法是:

registerUser() {
    // ..
}

因此角度解析器找不到html中定义的register方法。

答案 1 :(得分:0)

  

json输入的意外结束

当您因任何原因(错误的网址,服务器已关闭,端口已关闭)而导致http调用失败并且服务器返回的响应不是{{1}时,通常会发生此错误}。

查看您的网络标签,查看您正在制作的http cal,以及您在响应标签中获得的内容。

基本上这个错误通常意味着,Javascript无法解析它本来应该是JSON

的内容

答案 2 :(得分:0)

如果我是你,我会检查模板和ts文件中的拼写错误。

此外,您可以尝试只导入文件顶部的服务,只需将它们添加到构造函数中,如下所示:

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

我认为TS会为您完成作业。 然后onInit()或任何其他地方你可以写this.authService.someMethod()等。

确定“非功能”错误表示拼写错误/拼写错误。

如前所述,您的html模板中已存在register(),但ts文件中不存在src/main/resources/static/css。我还会重命名RegisterComponent的属性,以确保将来可以避免可能的拼写错误和错误。

答案 3 :(得分:0)

Unexpected end of json input可能是因为您没有从服务器提供有效的json。 我没有看到this._regsiterService.registerUser内的代码。但我相信有一个引发问题的response.json()调用。