我可以在angular4中从/向服务器获取和发布数据,但是为了获取发布的数据我必须刷新页面吗?我想知道我是否可以在不刷新页面或使用的情况下做到这一点:
IntervalObservable.create(5000)
.subscribe(
() => {
this.mysqlService.getMysqlData()
.subscribe(
res => this.usersMysql = res,
err => console.log(err.status)
);
}
);
service.ts文件:
// get mysql users Data
public getMysqlData(): Observable<any> {
return this.http.get('http://localhost/BackEndTest/getUsers.php')
.map( res => res.json());
}
// post data to the server
public addMysqlUserData(fname, lname) {
const url = 'http://localhost/BackEndTest/postUsers.php';
const headers = new Headers();
headers.append('Content-Type', 'application/x-www-form-urlencoded');
return this.http.post(url, {id: '', firstname: fname, lastname: lname}, {headers: headers})
.map(
(res: Response) => res.text())
.subscribe(res => {
console.log(res.toString());
});
}
后用户成分:
export class PostUsersComponent implements OnInit {
constructor(private mysqlService: MysqlService) { }
ngOnInit() {
}
addUser(fname: string, lname: string) {
console.log(fname + ' *** ' + lname);
if (this.mysqlService.addMysqlUserData(fname, lname)){
alert('Data Inserted Successfully');
}
}
}
get-users comonent:
getUsersMysql() {
this.mysqlServiceC.getMysqlData()
.subscribe(
res => this.usersMysql = res,
err => console.log(err.status)
);
}
感谢您的帮助
答案 0 :(得分:1)
我用这个解决方案解决了我的问题(我不知道它是否是最好的),在我添加的服务文件中:
newDataAdded = new EventEmitter<string>();
在我的post-users-component中,在addUser方法中:
this.mysqlService.newDataAdded.emit('new data added successfully');
在我的get-users-component中,我在构造函数中订阅了这个事件:
this.mysqlService.newDataAdded.subscribe(
(st: string) => {
this.getUsersMysql();
}
);
并且效果很好
感谢您的所有答案