Jesus Sandrea
Diego Burlando
Excelente @jesussandrea12
Yohan Estiven Arias Vasquez
Excelente tu aporte
Jesus Sandrea
Diego Burlando
Excelente @jesussandrea12
Yohan Estiven Arias Vasquez
Excelente tu aporte
servicio
public getLugar(id){ return this.afDB.object('lugares/'+id); }
componente
this.lugaresServices.getLugar(this.id) .valueChanges().subscribe(lugar => { this.lugar = lugar; });
Chema Muñoz
Ivan Cardozo
Estaría muy bueno que Platzi ponga almenos a los profesores a resolver nuestras dudas o a actualizar mínimo el código . Se que tengo que ser autodidacta , pero primero tengo que ver almenos una vez como se hacen estas cosas , porque adivino no soy.
Junior Enrique Rojas
andres flores
no veo la diferencia en los dos colocas los mismos parametros
this._router.navigate([’/crear’, ‘new’]);
Greivin Fonseca
ahora hay que poner el valuechanges()
<public getLugar(id){ return this.afDB.object('lugares/'+id).valueChanges(); }>
Jose Pech
Me salvaste! Gracias
Daniel Acero
trato de realizar esta actividad siguiendo a detalle las observaciones de mis compañeros pero me arroja el siguiente error
Alejandro Salguero Quirós
Hola! Revisa que la función getLugar() esté retornando algo, recuerda que aunque se te olvide poner el return el metodo va a seguir funcionando generando este tipo de errores
Daniel Acero
muchas gracias!!
Luis Troya
Otra opcion mientras los dos metodos hagan lo mismo
this.inputs.id = this.inputs.id || new Date().getTime();
De esta forma, solo generara un id si this.input.id es un falsy value (0, null o undefined)
Josué Estévez Fernández
Carlos Uriel de Jesus Sánchez González
manejo de parametros para identificar si es create or update
carlos Alberto Bedoya Ramirez
public actualizarLugar(lugar) { this.afDB.database.ref('lugares/' + lugar.id).update(lugar); }
carlos Alberto Bedoya Ramirez
Es mejor crear otro componente para actualizar y asi se evita tener tantos IFS
Noé Muñoz
Hasta ahora todo el curso muy entendible, clases corta y concisas, todo lo he entendido perfectamente, 😃
Rafael Jair Sanchez Alviso
Milciades Vargas Liz
se puede dejar la misma funcion y solo se realiza el cambio en la generacion del id
if(this.id == 'new'){ this.lugar.id = Date.now(); } this.lugaresService.guardarLugar(this.lugar); alert('Negocio guardado con exito'); this.lugar = {} ;
Alexis Antonio Moraga Gallardo
hola buenas, me esta arrojando este error
{
“error_message” : “You have exceeded your daily request quota for this API. We recommend registering for a key at the Google Developers Console: ”,
“results” : [],
“status” : “OVER_QUERY_LIMIT”
}
ya consegui la key desde la pagina que me muestra el error, pero donde la integro? ayuda, este problema no me deja continuar avanzando!!
Diego Forero
Team Platzipones la key como parámetro dentro de la url, ya deje un comentario con la documentación oficial donde dejaste una copia de este comentario.
Mariano Logarzo
Exactamente como dice GOLLUM23, la url que queremos obtener se verá así:
A esto sumaremos la dirección ingresada por el usuario.
Se puede usar la misma api que usamos en app.module.ts cuando importamos AgmCoreModule.
Usuario anónimo
UserGenial solucionaron el reto con una buena alternativa.
veronica oviedo
me surge una pregunta: No seria mas recomendable dejar de enviar los ids por la url y en su lugar mandarselo directamente al componente?
veronica oviedo
es casi imposible avanzar sin exceder el limite de consumo de la apis de google
Walter Enrique Ruiz Diaz
Aquí está mi aporte https://github.com/werd2000/mysquare
Walter Enrique Ruiz Diaz
La diferencia es que utilizo mapbox
Me paso que cuando pone el condicional con suscribe aparece un error, diciendo que .suscribe no es una funcion en fin. la solucion es esta:
if (this.id != 'new'){ this.lugaresService.getLugar(this.id) .valueChanges().subscribe(lugar => { this.lugar = lugar; }); }
Esto es como me ha funcionado a mí con los métodos de acceso a Cloud Firestore:
crear.component.ts
lugar:any = {}; id:any = null; constructor(private lugaresService: LugaresService, private route: ActivatedRoute) { this.id = this.route.snapshot.params['id']; if (this.id !== 'new'){ this.lugaresService.getLugar(this.id).subscribe(result =>{ console.log(result.data()); if (result.exists) { this.lugar = result.data(); } else { // result.data() will be undefined in this case console.log("No such document!"); } }); } }
lugares.service.ts
public getLugar(id){ console.log("Solicitando datos del Negocio: ", id); return this.db.collection('lugares').doc(id.toString()).get(); }
Cuando hacemos la edición de un lugar la edición funciona pero la url aun guarda el mismo id, entonces cuando creemos que estamos agregando uno nuevo estamos editando el anterior. para solucionar este problema tenemos que hacer lo siguiente:
import { Router } from '@angular/router';
private _router: Router
Método guardarLugar:
this._router.navigate(['/crear', 'new']);
Mas información -->
Mi codigo Completo:
import { Component, OnInit } from '@angular/core'; import { ActivatedRoute } from '@angular/router'; import { LugaresService } from '../../services/lugares.service'; import { Router } from '@angular/router'; @Component({ selector: 'app-crearnegocio', templateUrl: './crearnegocio.component.html', styleUrls: ['./crearnegocio.component.css'] }) export class CrearnegocioComponent implements OnInit { lugar: any = {}; id: any; constructor(private _lugaresService: LugaresService, private _activatedRoute: ActivatedRoute, private _router: Router) { this.id = this._activatedRoute.snapshot.params['id']; if (this.id !== 'new') { this._lugaresService .getLugar(this.id) .subscribe(lugar => { this.lugar = lugar; }); } } ngOnInit() { } public guardarLugar() { const direccion = this.lugar.calle + ',' + this.lugar.ciudad + ',' + this.lugar.pais; this._lugaresService .obtenerGeoData(direccion) .subscribe(result => { this.lugar.lat = result.json().results[0].geometry.location.lat; this.lugar.lng = result.json().results[0].geometry.location.lng; if (this.id !== 'new') { this._lugaresService.editLugar(this.lugar); alert('Negocio Editado con Exito'); this._router.navigate(['/crear', 'new']); } else { this.lugar.id = Date.now(); this._lugaresService.guardarLugar(this.lugar); alert('Negocio Creado con Exito'); this._router.navigate(['/crear', 'new']); } this.lugar = {}; }, error => console.log(error)); } }
Esta es mi solución (usando un nuevo componente para editar):
1- Obtengo el lugar de Firebase reutilizando la función findPlace (ya se utiliza para la vista de detalles), también obtengo un id y un objeto place con la info del lugar
2- Creo una función updatePlace, que es muy parecida a savePlace, pero sin atribuir un ID porque ya lo tenemos
*No estoy muy seguro de si es la forma óptima de separar conceptos y si debería haber un updatePlace en el places.service, pero funciona perfectamente.
¡Agradezco sus comentarios!
import { Component } from '@angular/core'; import { ActivatedRoute } from '@angular/router'; import { PlacesService } from '../services/places.service'; @Component({ selector: 'app-edit', templateUrl: './edit.component.html' }) export class EditComponent { id = null place:any = {} constructor(private route: ActivatedRoute, private placesService: PlacesService){ this.id = this.route.snapshot.params['id'] this.place = this.placesService.findPlace(this.id) .valueChanges().subscribe(place => { this.place = place; }); } // Esta función es como savePlace, pero sin modificar el ID // Quizá debería ir en el places.service ... Pero no veo mucha diferencia // porque reutilizamos los métodos ya existentes, con pequeñas modificaciones updatePlace(){ let address = this.place.street + ',' + this.place.town + ',' + this.place.country this.placesService.getGeoData(address) .subscribe(result => { this.place.lat = result.json().results[0].geometry.location.lat this.place.lng = result.json().results[0].geometry.location.lng this.placesService.savePlace(this.place) alert('Business updated successfully!') }) } }
Yo cree otro componente para editar basado en el de crear
import { Component } from '@angular/core'; import { ActivatedRoute } from '@angular/router'; import { LugaresService } from '../services/lugares.service'; @Component({ selector: 'app-edit', templateUrl: './edit.component.html' }) export class EditComponent { lugar:any = {}; id = null; constructor(private lugaresService: LugaresService, private route: ActivatedRoute) { this.id = this.route.snapshot.params['id']; this.lugaresService.buscarLugar(this.id) .valueChanges().subscribe((lugar)=>{ this.lugar = lugar console.log(lugar) }); } guardarLugar(){ var direccion = this.lugar.calle +','+this.lugar.ciudad +','+this.lugar.pais; this.lugaresService.obtenerGeoData(direccion) .subscribe( (result) => { this.lugar.lat = result.json().results[0].geometry.location.lat; this.lugar.lng = result.json().results[0].geometry.location.lng; this.lugaresService.guardarLugar(this.lugar); alert('Negocio Editado con Exito'); }) } }