Angular 2发送数组另一页

时间:2017-09-15 21:36:23

标签: angular typescript

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



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']);
      }
    )
  }
}
&#13;
&#13;
&#13;

&#13;
&#13;
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 {
  }
&#13;
&#13;
&#13;

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

1 个答案:

答案 0 :(得分:0)

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

&#13;
&#13;
@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() {

  }

}
&#13;
<!-- Parent html -->

<app-child [childData]="parentData"></app-child>
&#13;
&#13;
&#13;

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

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

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

&#13;
&#13;
@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;
    });
  }

}
&#13;
&#13;
&#13;

使用这种方法,您会注意到数据不会立即返回,代码也不会等待数据。您必须执行与subscribe()块内的数据相关的任何TypeScript逻辑才能使其正常工作。当值发生变化时,HTML将自行更新。当BehaviorSubject的值发生变化时,使用此方法,订阅getData()方法的任何地方也将接收新数据。

如果您需要任何帮助,请发表评论。