簡體   English   中英

如何將數據從組件傳遞到服務?

[英]how to pass data from component to service?

我有一個 tasks.component.ts 文件,其中的代碼是

addTask($event: Event) {
      alert(this.name);

      var newTask ={
      name: this.name
     }

//alert(this.tasks.push(newTask));

 this.taskServices.addTask(newTask)
    .subscribe(tasks => {
    this.tasks.push(tasks);
   });

  }

task.services.ts 這是我的 taskservices 文件..在我寫的

 addTask(newTask){
 var headers = new Headers();
 headers.append('ContentType','application/json');
 return this.http.post('http://localhost:3000/edata',JSON.stringify(newTask)).map(res => res.json());
 }

我正在嘗試傳遞數據“this.tasks.push(tasks);” 它應該將數據傳遞給 task.services.ts 中的 addTask(newTask){...}

但它沒有將數據推送到 addTask(){...} 怎么做,我的代碼有什么問題嗎?

您必須將newtask變量設置為組件級別,並且需要提供提供程序並訪問該 newTask 方法,如下所示:

export class TasksComponent implements OnInit, AfterViewInit {
      newTask;

      constructor(private _taskService:taskService) { }

        addTask($event: Event) {
          alert(this.name);

          this.newTask ={
          name: this.name
         }

        this._taskService.addTask(this.newTask);


        ngOnInit() {
             this.taskServices.addTask(newTask)
                .subscribe(tasks => {
                this.tasks.push(tasks);
               });
        }
    }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM