angular 2 http请求状态码0

时间:2016-09-19 15:50:00

标签: angularjs angular

items.component.ts

    import {Component, OnInit} from '@angular/core';
    import {Item} from './Item';
    import {ItemService} from "./item.service";
    import {Router} from "@angular/router";

    @Component({
      moduleId: module.id,
      selector: 'my-items',
      templateUrl: 'template/items.component.html',
      styleUrls: ['template/items.component.css']
    })
    export class ItemsComponent implements OnInit {
      errorMessage: string;
      title = 'Hero Tour';
      items: Item[];
      selectedItem: Item;

      constructor(private  router: Router, private itemservice: ItemService) {

      }

      onSelect(item: Item) {
        this.selectedItem = item;
      }

      ngOnInit() {
         this.itemservice.getItems().subscribe(items=>this.items = items);
        //if not comment this can call api add new item and push it into array
        //this.itemservice.create('Test Add').subscribe((item:Item)=>this.items.push(item) );
      }

      goDetail(): void {
        let link = ['/detail', this.selectedItem.ItemId];
        this.router.navigate(link);
      }

      addItem(name: string): void {
        name = name.trim();
        if (!name) {
          return;
        }

        this.itemservice.create(name).subscribe(
          (item: Item) => this.items.push(item),
          (error: any) => {
            this.errorMessage = <any>error;
            console.log(this.errorMessage);
            console.log('xxxxxxxxxxxxxxxx');
            this.router.navigate(['/items'])
          },
          ()=>this.router.navigate(['/items'])
        );


      }

    }


items.component.html
    <div>
      <label>Item Name:</label><input #itemNane>
      <button (click)="addItem(itemNane.value); itemNane.value=''">Add</button>
    </div>
    <h2>My Items</h2>
    <ul class="heroes">
      <li *ngFor="let item of items" [class.selected]="item===selectedItem" (click)="onSelect(item)">
        <span class="badge">{{item.ItemId}}</span>{{item.ItemName}}
      </li>
    </ul>
    <div *ngIf="selectedItem">
      <h2>{{selectedItem.ItemName | uppercase}} is my item</h2>
      <button (click)="goDetail()">View Details</button>
    </div>

在ngOnInit()中使用
this.itemservice.create('Test Add')。subscribe((item:Item)=&gt; this.items.push(item)
可以调用web api添加一个名为“Test Add”的新项目 但是当我点击添加按钮时 请求显示在firefox控制台上,但服务器未收到此请求,然后重定向到索引 firefox console log error

1 个答案:

答案 0 :(得分:0)

当我添加类型属性错误是固定的 &LT; button type =“button”(click)=“addItem(itemNane.value); itemNane.value =''”&gt; Add&lt; /按钮&GT;