Estoy tratando de abrir una ventana ngx Modal después de una llamada http realizada desde una aplicación angular.
Aquí está el código de app.module.ts
import { NgModule } from '@angular/core'; import { BrowserModule } from '@angular/platform-browser'; import { ReactiveFormsModule } from '@angular/forms'; import { AppComponent } from './app.component'; import { HttpClientModule } from '@angular/common/http'; import { BrowserAnimationsModule } from '@angular/platform-browser/animations'; import { ModalModule } from 'ngx-bootstrap/modal'; @NgModule({ declarations: [ AppComponent ], imports: [ BrowserModule, HttpClientModule, ReactiveFormsModule, BrowserAnimationsModule, ModalModule.forRoot(), ], providers: [], bootstrap: [AppComponent] }) export class AppModule { }Aquí está el código del componente en el que se realiza la llamada http
import { Component, TemplateRef, ViewChild } from '@angular/core'; import { HttpClient, HttpHeaders } from '@angular/common/http'; import { FormControl, FormGroup, Validators } from '@angular/forms'; import { Tour } from './Models/Tour/tour.model'; import { BsModalService, BsModalRef } from 'ngx-bootstrap/modal'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.scss'] }) export class AppComponent { title = 'AnguLearn'; public fGroup: FormGroup; public Tours : Tour[] = []; public Empty = false; @ViewChild('template', {static: true}) modalr? : TemplateRef<any>; modalRef?: BsModalRef; constructor(private modalService: BsModalService){ } public getDatas(){ const httpOptions = { headers: new HttpHeaders({ 'Content-Type': 'application/json; charset=utf-8' }) }; this.http.post<[Tour]>("https://localhost:44387/api/tours", filter_details, httpOptions).subscribe( (response)=>{ this.Tours = response; this.Empty = response.length <= 0; this.openModal(this.modalr);//I want to open a modal box here }, errors=>{ console.log(errors)}); } openModal(template: TemplateRef<any>) { this.modalRef = this.modalService.show(template); } } No funcionó, y no compiló. Siempre recibo el siguiente error en la línea con this.openModal(this.modalr); :
Argumento de tipo 'TemplateRef | undefined' no se puede asignar a un parámetro de tipo 'TemplateRef'. El tipo 'indefinido' no se puede asignar al tipo 'TemplateRef'.
¿Alguna idea?
Tienes un error de tipo aquí.
@ViewChild('template', {static: true}) modalr? : TemplateRef<any>; ? significa valor opcional para modalr . Si es cierto, debe cambiar sus métodos en esta forma de escribir. O si está seguro de tener valor en TemplateRef , ¿simplemente elimínelo ? firmar desde la sintaxis de propiedad como esa:
@ViewChild('template', {static: true}) modalr : TemplateRef<any>;Si no está seguro de tener el valor de la plantilla, haga eso:
openModal(template?: TemplateRef<any>) { if (template) { this.modalRef = this.modalService.show(template); } }