使用Angular 2中的Resolve Guard解析多个数据片段

时间:2016-11-03 18:36:32

标签: angular angular2-routing

我有一个PollDetailResolve类,可以在导航到poll-detail页面之前解析一个轮询。但是,我还需要解析一个单独的数据(我们称之为canVote的布尔值),它也将使用PollService。

解决两个或多个数据的最佳方法是什么?

@Injectable()
export class PollDetailResolve implements Resolve<Poll> {
  constructor(private pollService: PollService, private router: Router) { }

  resolve(route: ActivatedRouteSnapshot): Observable<Poll> | boolean {
    let id = route.params['id'];

    return this.pollService.getById(id)
      .map(poll => {
        if (poll) {
          return poll;
        } else {
          console.log("NOT FOUND!"); // TODO reroute
        }
      },
      err => {
        console.error(err);
      });
  }
}

我的poll-detail ngOnInit()函数:

  ngOnInit(): void {
    this.route.data.forEach((data: { poll: Poll }) => {
      this.poll = data.poll;
      this.sharePoll(this.poll);
    });
  }

2 个答案:

答案 0 :(得分:1)

您可以使用package ... import .... public class ScheduleActivity extends AppCompatActivity { private LinearLayout parentEventLayout; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_schedule); parentEventLayout = findViewById(R.id.parent_linear_layout); } public void onAddEvent(View v) { LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE); final View rowView = inflater.inflate(R.layout.event, null); // Add the new row before the add field button. parentEventLayout.addView(rowView, parentEventLayout.getChildCount() - 1); } public void onToggle(View v) { Button btn = findViewById(R.id.pbToggle); btn.setText((btn.getText() == ">>") ? "<<" : ">>"); } } 轻松解析多个可观察物。

您可以在以下答案中查看其工作原理:https://stackoverflow.com/a/53704018/6572208

答案 1 :(得分:0)

如果它们是可观察的,您可以使用combineLatest运算符连接它们,然后返回流。以下是一个示例:https://github.com/Reactive-Extensions/RxJS/blob/master/doc/api/core/operators/combinelatest.md