Sending an array from one page to another using Angular 2

I am currently working on a weather application using Angular. As a beginner in Angular, I am facing an issue with sending data to the second page to display the weather information of the selected city. Can someone please help me identify where the problem lies? Your assistance is greatly appreciated.

export class ForecastComponent implements OnInit, OnDestroy {
  
  constructor(private service: WeatherService, private router: Router, private route: ActivatedRoute) { }

  public items: Array<string> = ["ADANA", "ADIYAMAN", "AFYONKARAHİSAR", "AĞRI", "AMASYA", "ANKARA", "ANTALYA", "ARTVİN"];

  public selectedValue: BaseModel;
  value: any = {};
  weatherClass: Weather;

  ngOnInit() {}

  ngOnDestroy(): void {
    this.route.data.subscribe(
      (data: { weatherClass: Weather }) => {
        this.weatherClass = data.weatherClass;
      }
    )
  }
  public selected(value: any): void {
    console.log('Selected value is: ', value);
  }

  public removed(value: any): void {
    console.log('Removed value is: ', value);
  }

  public typed(value: any): void {
    console.log('New search input: ', value);
  }

  public refreshValue(value: any): void {
    this.value = value;
  }
  sendCityWeather(value: Array<BaseModel>) {
    this.service.otherWeather(this.value.text).subscribe(
      (data) => {
        this.weatherClass = new Weather(data.name, data.main.temp, data.weather[0].description, data.main.temp_min, data.main.temp_max, data.weather[0].icon);
        console.log(this.weatherClass);
        this.router.navigate(['/weather']);
      }
    )
  }
}

export class WeatherComponent implements OnInit, OnDestroy {

  weatherClass: Weather;
  value: any = {};

  constructor(private service: WeatherService, private route: ActivatedRoute, private router: Router) {}
  
  ngOnInit() {
    this.service.otherWeather(this.value.text).subscribe(
      (data: Weather) => {
        this.weatherClass = data;
      }
    )
  }

  ngOnDestroy(): void {
  }

export class WeatherService {

  weatherClass: Weather;

  constructor(private http:Http) { }

  otherWeather(city:string){
    return this.http.get(`http://api.openweathermap.org/data/2.5/weather?appid=0f3fb9fa31ad3d41f1bb2bd0841c3f2f&q=${city}&units=imperial&cnt=10`).map((response:Response) => response.json());
  
  }
}

Answer №1

When it comes to passing data into components, there are two primary methods: utilizing EventEmmiters @Output() or EventReceiver @Input(), or employing a service. To pass data from a parent component to a child component, you can utilize @Input() in the child component. See the example below:

@Component({
  selector: 'app-parent',
  templateUrl: './child.component.html',
  styleUrls: ['./child.component.css']
})

export class ParentComponent implements OnInit {

  parentData: Weather;

  constructor(private service: WeatherService, private route: ActivatedRoute, private router: Router) {}

  ngOnInit() {

  }

}


@Component({
  selector: 'app-child',
  templateUrl: './child.component.html',
  styleUrls: ['./child.component.css']
})

export class ChildComponent implements OnInit {

  @Input() childData: Weather;

  constructor(private service: WeatherService, private route: ActivatedRoute, private router: Router) {}

  ngOnInit() {

  }

}
<!-- Parent html -->

<app-child [childData]="parentData"></app-child>

The above code snippet demonstrates how to pass data into the app-child component, but remember that this approach necessitates importing the child component into the parent component.

In my opinion, the preferred method is using a service as it can be added as a service rather than a component. Here's an example implementation:

export class WeatherService {

  weatherClass: Weather;
  
  //BehaviorSubject can store the last value given until the service destroyed or otherwise changed
  private data: BehaviorSubject<Weather> = new BehaviorSubject(null);

  constructor(private http: Http) {}

  otherWeather(city: string) {
    return this.http.get(`http://api.openweathermap.org/data/2.5/weather?appid=0f3fb9fa31ad3d41f1bb2bd0841c3f2f&q=${city}&units=imperial&cnt=10`).map((response: Response) => response.json());
  }
  
  setData(value: Weather) {
    this.data.next(value);
  }
  
  getData(): Observable<Weather> {
    return this.data.asObservable();
  }
}

@Component({
  selector: 'app-parent',
  templateUrl: './child.component.html',
  styleUrls: ['./child.component.css']
})

export class ParentComponent implements OnInit {

  parentData: Type = ["ADANA", "ADIYAMAN", "AFYONKARAHİSAR", "AĞRI", "AMASYA", "ANKARA", "ANTALYA", "ARTVİN"];

  constructor(private service: WeatherService, private route: ActivatedRoute, private router: Router) {}

  ngOnInit() {
   this.service.otherWeather(this.value.text).subscribe( (data: Weather) => { 
    this.service.setData(data);
    });
  }

}


@Component({
  selector: 'app-child',
  templateUrl: './child.component.html',
  styleUrls: ['./child.component.css']
})

export class ChildComponent implements OnInit {

  childData: Weather;

  constructor(private service: WeatherService, private route: ActivatedRoute, private router: Router) {}

  ngOnInit() {
    this.service.getData().subscribe((values: Weather) => {
      this.childData = values;
    });
  }

}

By employing this method, the data may not be returned instantaneously and the code will need to wait for the data. Any TypeScript logic related to the data must be handled within the subscribe() block for proper functionality. The HTML will automatically update when the value changes. This technique ensures that any subscribed elements to the getData() method will receive updated data whenever the value of BehaviorSubject alters.

If further assistance is needed, feel free to leave a comment.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Utilizing Omit for the exclusion of nested properties within a TypeScript interface

One of the components in a library I am using is defined like this: export interface LogoBoxProps { img: React.ReactElement<HTMLImageElement>, srText?: string, href?: LinkProps['href'] } export type LogoBoxType = React.FC<React.HT ...

Angular2: AuthGuard malfunctioning with browser navigation controls

My AuthGuard setup works flawlessly during normal navigation within the application (see code below). Now, consider this scenario: A user goes to /content/secured-content, which requires authentication => they are redirected to /authentication/login d ...

What is the syntax for implementing this function in TypeScript?

When developing applications in react and typescript, I find myself frequently creating helper functions. However, there are two key points that always give me pause. One of my functions is provided below, showcasing the common dilemmas I face. What shoul ...

Utilizing Bootstrap.css in various Angular modules

Is there a way to utilize bootstrap.css in specific modules rather than applying it to the entire application? I wish to avoid adding Bootstrap.css to index.html or styles of angular.json, and only use it in certain modules. In my project, I have two dis ...

Navigating Timezones with PrimeNG Calendar Component <p-calendar>

I am experiencing an issue with PrimeNG in a multi-user environment where each user is in a different timezone. I need all users to submit their form data in EST, but it seems like the browser is converting the dates to the user's local timezone upon ...

TypeScript PatchBaseline with AWS CDK

I am currently working with the AWS CDK and TypeScript, utilizing the @aws-cdk/aws-ssm library to create a PatchBaseline. While I have successfully created the Patch baseline, I'm encountering difficulties when attempting to define approvalRules. I ca ...

What is the use of the mongoose $gt operator in an Express application built with

I am searching for users whose tokens have not yet expired. try { const user = await User.findOne({ resetToken: passwordToken, resetTokenExpiration: { $gt: Date.now() }, _id: userId, }); if (!user) { throw new NotFoundEr ...

Substitute a particular element within a text

I'm currently working on an Angular 9 application where I'm implementing search filters for the Shopify Graphql API. As part of this process, I am constructing a query which looks like: first: 1, query: "tag:'featured-1'", af ...

Error in Angular 4: Undefined property 'replace' causing trouble

I've been trying to use the .replace() JavaScript function in Angular 4 to remove certain characters from a string. Here is the code snippet from my component: @Component({...}) export class SomeComponent implements OnInit { routerUrl: string = &apo ...

Is there a way to configure Angular CLI to enable loading a favicon with a content hash for its filename?

I am looking to cache my website's favicon in the same way I cache css, js, and png files by setting an expires header far into the future. However, I am struggling to figure out how to achieve this. Most resources I come across suggest using a link i ...

Expanding Angular FormGroup Models with TypeScript

I've developed a foundational model that serves as a base for several other form groups. export class BaseResource { isActive: FormControl; number: FormControl; name: FormControl; type: FormControl; constructor( { ...

Is it secure to transmit Tenant ID's as GET parameters to the API in a Multi-Tenant database environment?

When working with a Multi-Tenant database, is it secure to pass Tenant ID's as query string parameters to the API while using popular JavaScript-based UI platforms like Angular or Vue and ensuring both the site and the API are HTTPS? For example, let ...

Navigating between two different HTML pages using Angular 2 routing

In my Angular2 application, I have both a front-end section and an admin interface. The front-end section is styled with its own unique set of styles defined in the index.html file. On the other hand, the admin interface has a completely different set of ...

The cookie value is blank once after moving to the second page

I'm facing an issue with 2 domains where performing an action on the first domain results in setting a cookie that should be accessible on both domains. However, when trying to read the value of this cookie on the second domain, it appears empty. Can ...

Import components exclusively from the root/app directory in Angular 2

In my angular2 project, I used angular-cli version 1.0.0-beta.8 and angular version 2.0.0-rc.3. After running ng new or ng init, the directory structure created is as follows: create .editorconfig create README.md create src\app\app.compon ...

Implement a personalized Laravel Dusk selector with the attribute data-dusk

In the world of Laravel Dusk, the default selector hunts for the dusk="something" attribute in your HTML. If you want to dive deeper into this topic, check out this resource. However, when it comes to compatibility with Typescript for React/Vue, ...

How Keyof can render an object undefined and prevent accurate verification

Encountering TS2532 error: Object is possibly 'undefined' while attempting to access an object's value by dynamically selecting the key. TypeScript seems to be restricting me from checking the field values, and I'm unsure of the underly ...

How to utilize Enzyme to call a React prop in TypeScript

I'm currently in the process of converting my Jest tests from Enzyme to TypeScript, and I've come across a specific case that I'm unsure how to resolve. Essentially, I'm attempting to invoke a function passed as a prop to a sub-componen ...

I encountered an issue while trying to implement a custom pipe using the built-in pipe

My custom pipe seems to be functioning well, except for the built-in pipes not working within it. I've imported Pipe and can't figure out what could be causing the issue. Below is the code with the errors: import { Pipe, PipeTransform } from &a ...

Leverage TypeScript AngularJS directive's controller as well as other inherited controllers within the directive's link function

I am currently developing an AngularJS directive in TypeScript for form validation. I am trying to understand how to utilize the directive's controller and inherit the form controller within the directive's link function. Thank you in advance! ...