【发布时间】:2019-11-13 04:01:47
【问题描述】:
我正在开发基于单页应用程序 CRUD 的 API,我正在通过 使用 JWT 从前端到后端的数据工作正常。在后端我将数据保存在数据库中,然后获取所有数据并作为对前端的响应返回,这工作正常。
在前端,我在响应中获取数据并通过服务传递给另一个组件。基本上,我通过名为共享服务的服务将数据从创建组件传递到显示组件。正在传递的数据(来自后端的响应是一组 Javascript 对象)。
问题是数据没有到达显示组件,因为我想在它到达显示组件后循环遍历对象数组并将它们作为表格显示在视图 (show.component.html) 上
请帮忙?
创建组件
import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router';
import { SharedService } from 'src/app/Services/shared.service';
@Component({
selector: 'app-create',
templateUrl: './create.component.html',
styleUrls: ['./create.component.css']
})
export class CreateComponent implements OnInit {
public form = {
sponsorFirstName: null,
sponsorSurName: null,
sponsorEmail: null,
sponsorPhone: null,
nationality: null,
childFirstName: null,
childAge: null,
childSurName: null,
childGender: null
};
public error = null;
constructor(
private router: Router,
private Shared : SharedService) { }
onSubmit(){
this.Auth.submitFormData(this.form).subscribe(
data => this.handleResponse(data),
error => this.handleError(error)
);
}
handleResponse(data){
//console.log(data.data);
//pass the data to the shared service
this.Shared.createData(data.data);
//redirect to show-data component whereby I show the data in a table
this.router.navigateByUrl('/show-data');
}
handleError(error){
this.error = error.error.errors;
}
ngOnInit() {
}
}
共享服务
import { Injectable } from '@angular/core';
import { BehaviorSubject } from 'rxjs';
import { TokenService } from './token.service';
@Injectable({
providedIn: 'root'
})
export class SharedService {
private userData = new BehaviorSubject;
checkUser$ = this.userData.asObservable();
createData(data:any){
this.userData.next(data);
}
constructor(private Token : TokenService) { }
}
Show.component.ts 文件
import { Component, OnInit } from '@angular/core';
import { SharedService } from 'src/app/Services/shared.service';
@Component({
selector: 'app-show',
templateUrl: './show.component.html',
styleUrls: ['./show.component.css']
})
export class ShowComponent implements OnInit {
public userData;
constructor(
private Shared : SharedService,
) { }
ngOnInit() {
this.Shared.checkUser$.subscribe(message => this.userData = message);
}
}
【问题讨论】:
标签: arrays angular components communication