如何将数据发布到服务器

时间:2018-10-26 10:51:12

标签: javascript angular typescript angular6 json-server

我有一个简单的angular 6应用程序,具有“关注”和“取消关注”按钮,如您现在所见,当您单击关注人数增加时,我要将这些关注者号码保存到json服务器。

这是指向json服务器文档的链接:https://www.npmjs.com/package/json-server

以下是正在尝试做的演示:demo 这是我的json文件

  "data": [
    {
      "id": 1,
      "following": 121,
      "followers": 723,
    } 
  ],

这是html

<div class="container">
  <div class="row">
    <p class="col">{{numberOffollowers}}</p>
    <button class="col btn btn-success" (click)="followButtonClick()">Follow</button>
    <button class="col btn btn-danger" (click)="unfollowButtonClick()">Unfollow</button>
  </div>
</div>

这是服务

import { Injectable } from '@angular/core';
import { Statuses} from '../model/statuses';
import { HttpClient } from '@angular/common/http';

@Injectable()
export class UsersService {

  status: Statuses[];
  constructor(private http: HttpClient) { }
  statusUrl = 'http://localhost:3000/statuses';

  getStatuses() {
    return this.http.get<Statuses[]>(this.statusUrl);
  }
  addStatus(status: Statuses) {
   return this.http.patch(this.statusUrl, status);
  }
}

这是ts文件:

import { Component, Input } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { UsersService } from './service/users.service';
import { Statuses} from './model/statuses';
@Component({
  selector: 'like-box',
  templateUrl: 'like.component.html',
  styleUrls: [ './like.component.css' ]
})
export class LikeComponent  {
 numberOffollowers : number = 69;
  status: Statuses[];

  constructor(private http: HttpClient, private usersService: UsersService) { }

  followButtonClick() {
    this.numberOffollowers++;
  }

  unfollowButtonClick() {
    this.numberOffollowers--;
  }

   addStatus() {
    this.usersService.addStatus(this.numberOffollowers)
    .subscribe(data => {
      this.status.push(this.numberOffollowers);
    });
  }
}
通过此链接app通过

访问我的应用

您可以看到它不起作用,我需要在我的应用程序中进行哪些更改才能将这些关注者编号保存到json服务器?

2 个答案:

答案 0 :(得分:0)

您已在类似组件中添加了功能-addStatus() 但我看不到该函数的调用 您还需要添加状态按钮并调用该函数

答案 1 :(得分:0)

单击按钮时,您没有调用addStatus方法,而只是更新了numberOfFollowers

import { Component, Input } from '@angular/core';
import { UsersService } from './service/users.service';
import { Statuses} from './model/statuses';
@Component({
  selector: 'like-box',
  templateUrl: 'like.component.html',
  styleUrls: [ './like.component.css' ]
})
export class LikeComponent  {
 numberOffollowers : number = 69;
  status: Statuses[];

  constructor( private usersService: UsersService) { }

  followButtonClick() {
    this.numberOffollowers++;
    this.addStatus()
  }

  unfollowButtonClick() {
    this.numberOffollowers--;
     this.addStatus()
  }

   addStatus() {
    this.usersService.addStatus(this.numberOffollowers)
    .subscribe(data => {
      this.status.push(this.numberOffollowers);
    });
  }
}