Reputation: 1658
I can get and post data from/to the server in angular4 , but for get the posted data i must refresh the page? and i want to know if i can do that without refreshing the page or using :
IntervalObservable.create(5000)
.subscribe(
() => {
this.mysqlService.getMysqlData()
.subscribe(
res => this.usersMysql = res,
err => console.log(err.status)
);
}
);
service.ts file:
// 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());
});
}
post-users-component:
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)
);
}
thanks for your help
Upvotes: 0
Views: 3071
Reputation: 1658
I resolved my problem with this solution (i dont know if it's the best), in my service file i added :
newDataAdded = new EventEmitter<string>();
and in my post-users-component, in addUser method :
this.mysqlService.newDataAdded.emit('new data added successfully');
and in my get-users-component i subscribed to this event in constructor:
this.mysqlService.newDataAdded.subscribe(
(st: string) => {
this.getUsersMysql();
}
);
and it works very well
thanks for all your answers
Upvotes: 1