Angular 2发送数组另一页 [英] Angular 2 send array another page

查看:60
本文介绍了Angular 2发送数组另一页的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Angular开发天气应用程序.我是Angular的新手.我想携带我选择的城市的天气信息.但是我无法将数据发送到第二页.问题出在哪儿?预先感谢您的帮助.

I am developing weather application with Angular.I'm new to Angular. I want to bring the weather information of the city I selected. But I could not send the data to the second page. Where is the problem? Thank you in advance for your help.

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());
  
  }
}

推荐答案

有两种方法可以使用EventEmmiters @Output()EventReceiver @Input()或通过服务将数据传递到组件中. 您可以使用子组件中的@Input()将数据从父组件传递到子组件.这是一个示例:

There are two ways you can pass data into components, using EventEmmiters @Output() or EventReceiver @Input() or with a service. You can pass data from parent component to a child component with @Input() in the child component. Here is an example:

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

export class ParentComponet 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 ChildComponet implements OnInit {

  @Input() childData: Weather;

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

  ngOnInit() {

  }

}

<!-- Parent html -->

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

以上内容会将数据传递到app-child,但是此方法要求您将子组件导入到父组件.

The above will pass data into the app-child, but this method requires you to import the child component to the parent component.

我更喜欢服务方法,因为它可以作为服务而不是作为组件添加.下面是一个示例:

I prefer the service approach as it can be added as a service and not as a component. Below is an example of this:

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 ParentComponet 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 ChildComponet implements OnInit {

  childData: Weather;

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

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

}

使用这种方法,您会注意到数据不会立即返回,并且代码不会等待数据.您必须执行与subscribe()块内的数据相关的所有TypeScript逻辑,该逻辑才能起作用.当值更改时,HTML会自动更新.当BehaviorSubject的值更改时,使用此方法,预订getData()方法的任何地方还将接收新数据.

With this approach, you'll notice that the data is not returned straightaway and the code would not wait for data. You'll have to do any TypeScript logic related to data within the subscribe() block for it to work. HTML will update itself when the value changes. Using this method when the value of BehaviorSubject changes, anywhere that is subscribed to getData() method will also receive new data.

如果需要帮助,请删除评论.

Drop a comment if you need any help.

这篇关于Angular 2发送数组另一页的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆