Node.js 虽然通过的路线正确,但“按id编辑”在角度模式下不起作用

Node.js 虽然通过的路线正确,但“按id编辑”在角度模式下不起作用,node.js,angular,routing,Node.js,Angular,Routing,当用户正在编辑但它不工作时,我想在表单中编辑并显示值。Angular前端正在捕获正确的路由,但没有从后端获取数据,也没有调用api。内容未显示在浏览器上。如果你想看的话,我也附上git存储库链接。执行编辑的路径是,然后单击编辑按钮。下面我附上编辑blog.component.html代码 <h3>Edit this blog</h3> <div class="row" style="text-align:left"> <div

当用户正在编辑但它不工作时,我想在表单中编辑并显示值。Angular前端正在捕获正确的路由,但没有从后端获取数据,也没有调用api。内容未显示在浏览器上。如果你想看的话,我也附上git存储库链接。执行编辑的路径是,然后单击编辑按钮。下面我附上编辑blog.component.html代码

    <h3>Edit this blog</h3>
    <div class="row" style="text-align:left">
      <div class="col-md-12">
        <form #createBlogForm="ngForm" (ngSubmit)="editThisBlog()">

          <div class="form-group">


            <label>Blog Title</label>
            <input type="text" name="blogTitle" [(ngModel)]="currentBlog.title" #title="ngModel" class="form-control" placeholder="Enter blog Title"
              required>

          </div>
          <div [hidden]="title.valid || title.pristine" class="alert alert-danger">
           Blog Title is required 
          </div>

          <div class="form-group">
            <label>Description</label>
            <input type="text" name="blogDescription" [(ngModel)]="currentBlog.description" #description="ngModel" class="form-control" placeholder="Enter Description"
              required>
          </div>
          <div class="form-group">
            <label>Enter the blog body</label>
            <textarea name="blogBodyHtml" [(ngModel)]="currentBlog.bodyHtml" #bodyHtml="ngModel" class="form-control" rows="3" required></textarea>
          </div>
          <div class="form-group">
            <label>Category</label>
            <select [(ngModel)]="currentBlog.category" #category="ngModel" name="blogCategory" class="form-control" id="category" required>
                  <option *ngFor="let category of possibleCategories" [value]="category">{{category}}</option>
                </select>
          </div>


          <button type="submit" class="btn btn-default" [disabled]="!createBlogForm.form.valid">Edit the blog</button>
        </form>
      </div>

    </div>

  </div>
服务代码

import { catchError } from 'rxjs/operators';
import { HttpClient, HttpErrorResponse, HttpBackend, HttpParams } from '@angular/common/http';
import { Observable } from 'rxjs/Observable';
import { throwError } from 'rxjs';
import 'rxjs/add/operator/catch';
import 'rxjs/add/operator/do';

@Injectable({
  providedIn: 'root'
})
export class BlogpostService {

  public allBlogs;
  public currentBlog;
  errorData: {};
  isLoggedIn = false;

  public baseUrl = 'http://localhost:4000/api/v1/blogs';


  constructor(private _http:HttpClient, private handler: HttpBackend) { }

  public getAllBlogs(): any {
    let myResponse = this._http.get(this.baseUrl + '/all').pipe(
      catchError(this.handleError)
    );
    console.log(myResponse);
    return myResponse;
   }

   public getSingleBlogInformation(currentBlogId): any {
    let myResponse = this._http.get(this.baseUrl + '/view/' + currentBlogId).pipe(
      catchError(this.handleError)
    );
    return myResponse;
  }

  public createBlog(blogData): any {
    let myResponse = this._http.post(this.baseUrl + '/create', blogData);
    return myResponse;

  }

  public deleteBlog(blogId): any {
    let data = {}
    let myResponse = this._http.post(this.baseUrl + '/' + blogId + '/delete', blogId);
    return myResponse;

  }

  public editBlog(blogId, blogData): any {
    let myResponse = this._http.put(this.baseUrl + '/edit' + '/' + blogId, blogData);
    return myResponse;
  }

  public getUserInfoFromLocalStorage: any = () =>{
    return JSON.parse(localStorage.getItem('userInfo'));
  }

  public setUserInfoInLocalStorage: any = (data) =>{
    localStorage.setItem('userInfo', JSON.stringify(data))
  }

  public signinFunction(data): Observable<any>{

    const params = new HttpParams()

    .set('email', data.email)
    .set('password', data.password)


    return this._http.post(`${this.baseUrl}/login`, params);
  }

  private handleError(error: HttpErrorResponse) {
    if (error.error instanceof ErrorEvent) {
      // A client-side or network error occurred. Handle it accordingly.
      console.error('An error occurred:', error.error.message);
    } else {
      // The backend returned an unsuccessful response code.
      // The response body may contain clues as to what went wrong,
      console.error(`Backend returned code ${error.status}, ` + `body was: ${error.error}`);
    }
    // return an observable with a user-facing error message
    this.errorData = {
      errorTitle: 'Oops! Request for document failed',
      errorDesc: 'Something bad happened. Please try again later.'
    };
    return throwError(this.errorData);
  }

}
路线

数据对象如下所示

{"title":"Blog Title 2 Custom","description":"Blog description 2 Custom","bodyHtml":"<h3>Heading of the body CUSTOM</h3><p>This is the first blog data getting uploaded n blog project</p>","views":5,"isPublished":true,"category":"tech","author":"Decardo","tags":["english movies, action movies, comedy"],"_id":"5e1120d223416207d8ae5e1b","blogId":"nbfO8hJp","created":"2020-01-04T23:33:38.000Z","lastModified":"2020-01-04T23:33:38.000Z","__v":0}
{“title”:“Blog title 2 Custom”、“description”:“Blog description 2 Custom”、“bodyHtml”:“body Custom的标题”这是在Blog项目中上传的第一个Blog数据,,“views”:5,“isPublished”:true,“category”:“tech”,“author”:“Decardo”,“tags”:[“英语电影,动作电影,喜剧”],“\u id”:“5e1120d23416207d8ae5e1b”,“blogId”::“nbfO8hJp”,“创建”:“2020-01-04T23:33:38.000Z”,“上次修改”:“2020-01-04T23:33:38.000Z”,“_uv”:0}

只需按如下方式修复编辑按钮的路径:

<a [routerLink]="['/admin/edit', blog.blogId]" class="btn btn-info btn-sm">Edit</a>

要编辑博客的信息,您需要从blogpost服务调用editBlog方法,并将id(blogId)和主体(blogData)传递给它所以在服务器端,你得到的是一个id和一个主体,这是更新数据。你可以从request So req.body获得主体。你错过的是更新你找到的对象,这就是为什么我做了一个循环,用req.body中的新值更新Blog对象的值,并且只在更新后保存它。显然还有其他原因更新我们要修改的对象的方法。

尝试console.lognothing正在Consolery上生成
console.log的路径,该路径将遵循执行此函数时应命中的所有方法。是否没有为编辑api的节点控制器代码记录任何内容?没有任何内容。我认为它无法命中apithis工作得很好!你能详细解释一下你在控制器下添加的这个部分吗?else{for(让输入数据){result[key]=data[key];}另外,我需要每一个其他路由都是管理组件的子组件,因为我正在路由其余的组件以加载到管理组件中。哦,我刚刚发现您需要所有组件作为子组件。我将更新我的答案!请确保还原您在管理路由模块和“添加帖子”上所做的更改“按钮,因为如果你想让所有的孩子都处于管理之下,你做得很好。
app.put(baseUrl+'/edit/:blogId',blogController.editBlog);
{"title":"Blog Title 2 Custom","description":"Blog description 2 Custom","bodyHtml":"<h3>Heading of the body CUSTOM</h3><p>This is the first blog data getting uploaded n blog project</p>","views":5,"isPublished":true,"category":"tech","author":"Decardo","tags":["english movies, action movies, comedy"],"_id":"5e1120d223416207d8ae5e1b","blogId":"nbfO8hJp","created":"2020-01-04T23:33:38.000Z","lastModified":"2020-01-04T23:33:38.000Z","__v":0}
<a [routerLink]="['/admin/edit', blog.blogId]" class="btn btn-info btn-sm">Edit</a>
let editBlog = (req, res) => {
    const data = req.body;
    BlogModel.findOne({ 'blogId': req.params.blogId }, (err, result) => {

        if (err) {
            console.log(err)
            res.send(err)
        } else if (result == undefined || result == null || result == '') {
            console.log('No Blog Found')
            res.send("No Blog Found")
        } else {
          for (let key in data) {
            result[key] = data[key];
          }
          result.views += 1;
            result.save(function (err, result) {
                if (err) {
                    console.log(err)
                    res.send(err)
                }
                else {
                    console.log("Blog updated successfully")
                    res.send(result)
                }
            });// end result
        }
    });
};